SegmentFault 技术分享最新的文章
2020-10-01T10:32:28+08:00
https://segmentfault.com/feeds/blogs
https://creativecommons.org/licenses/by-nc-nd/4.0/
如何让你的搜索更高效
https://segmentfault.com/a/1190000025183943
2020-10-01T10:32:28+08:00
2020-10-01T10:32:28+08:00
苏生不惑
https://segmentfault.com/u/sushengbuhuo
1
<blockquote>苏生不惑第178 篇原创文章,将本公众号设为<code>星标</code>,第一时间看最新文章。</blockquote><p>这周四就是国庆节长假了,大家的心情可能都是这样的。 <br><img src="/img/remote/1460000025183958" alt="image.png" title="image.png"></p><p>关于搜索之前分享过 <a href="https://link.segmentfault.com/?enc=uRvXxfqhXNJnlRis9rLTqg%3D%3D.bxqaLdGns%2Byvw0KZyGFUXSPzUwDiZswy6YwkfHujTO5Dz%2BPgkgMYJMvJhgPNgWwuj29up4NyGH2nEzx5BDGlDw%3D%3D" rel="nofollow">那些你可能不知道的搜索奇技淫巧</a> ,<a href="https://link.segmentfault.com/?enc=kca6MtmDTW%2BIst8H4fVwyQ%3D%3D.S%2FnogShOiqlhF0ZqPNUZE2qqVRlTwl1w8WUZcArHrYQWU%2BFdh0PSgJouPQ8BmWGdnGXQPVF8ehP0BSe5XHPm4A%3D%3D" rel="nofollow">2020 最全百度网盘搜索,找电影资源不再愁</a> ,<a href="https://link.segmentfault.com/?enc=ET1T3AjP9Fuuy0oMZYjByA%3D%3D.0CVachsg%2FoZ0loTD0pMtt6p%2B0KvQ4dfRbfY3AQMdTejZrtXTcrvV2t0Cz3ELdQE6cvbj8WEwjcZvJPdVMDGx5g%3D%3D" rel="nofollow">2020 最全电子书搜索网站,找电子书不再愁</a> ,今天分享的是如何让你的搜索更高效。</p><p>先吐槽下,国内的互联网越来越不互联了,比如手机端看全文必须下载APP,有些产品(比如闲鱼)甚至没有网页端,robot.txt禁止搜索引擎抓取,把一个个APP的内容封闭起来,于是我们手机上安装的APP越来越多。<br><img src="/img/remote/1460000025183948" alt="image.png" title="image.png"><br><img src="/img/remote/1460000025183950" alt="image.png" title="image.png"></p><p>能用网页版我是不会安装APP的,电脑键盘打字多爽,大屏幕多爽,这里还是要点赞下b站和知乎,搜索引擎可以很方便的找到内容,不下载APP也完全可以使用他们的产品。</p><h3>去广告</h3><p>在百度搜索拼多多,第一个结果是个广告,居然不是拼多多官网,毕竟人家是给了钱的。<br><img src="/img/remote/1460000025183951" alt="image.png" title="image.png"></p><p>相比之下谷歌搜索就好多了,第一个就是官网,所以我一直推荐大家使用谷歌搜索和谷歌浏览器 ,谷歌还有很多产品 <a href="https://link.segmentfault.com/?enc=JxsI0YZzKivGfxZWAcwQDQ%3D%3D.ytYdf397qqAsmAf%2FO1qsxAIynAib1siYC6WUbwZ78Q%2FZ%2FZfWMPzUAk8gT1eT3RMxqUO9JQSwNRgsdakusqZnKg%3D%3D" rel="nofollow">那些在国内还能使用的谷歌产品</a><br><img src="/img/remote/1460000025183947" alt="image.png" title="image.png"></p><p>不过大多数人还是用百度居多,这里推荐一个 Chrome 扩展 广告终结者 ,它可以清除网页上的浮动广告,购物广告,恶意弹窗,跟踪代码,让你浏览网页更快更清爽, 而且支持绝大多数浏览器。<br><img src="/img/remote/1460000025183946" alt="image.png" title="image.png"><br>Chrome扩展地址<a href="https://link.segmentfault.com/?enc=R0HfRoEt1aN%2B45Jqnl5zWw%3D%3D.BGXW%2BCw6wg3gmEicFry0D4heM5WycH5y9PZhgs2aqJfVMSu4NKgk50q07tw2L7IZZZ0PHFMho10kT9RY2F%2BDvdJ5M%2FvjI4DyEhjYiekw6nBAHCeDYKVDdzQem%2B3BpSnv7W7sXOwO9NUHxcnofUvRYb%2BySjL%2BLEnnjHrT4vQ6f4%2FBtWMm%2FjIp6fZ9YGTcRyP1" rel="nofollow">https://chrome.google.com/web...</a> ,安装Chrome扩展方法见之前文章<a href="https://link.segmentfault.com/?enc=BjLH%2Bqf8T63gKyaSZyK%2FVQ%3D%3D.H%2BMd5AlsrD86IjLMLuOp%2BHg0n35ctCSC%2FSCg05Y3ZQlqB4sjRvlepHO7FxQ7P%2FMq7ruQ9usas7psibXU9%2FGPrg%3D%3D" rel="nofollow">上不了谷歌如何安装 Chrome 扩展?</a></p><p>安装扩展后再次百度搜索没有垃圾广告了,第一个就是官网,搜索效率明显提高了。<br><img src="/img/remote/1460000025183952" alt="image.png" title="image.png"></p><p>除了去除网页广告,它还有个实用功能就是去除视频广告,比如腾讯,优酷,爱奇艺这样的影视网站, 45秒的开头广告 。<br><img src="/img/remote/1460000025183949" alt="image.png" title="image.png"></p><p>安装好这个扩展后再次打开爱奇艺可以看到广告一晃而过就开始播放视频,看我录制了的GIF。<br><img src="/img/remote/1460000025183961" alt="iqiyi_ad.gif" title="iqiyi_ad.gif"></p><h3>搜索引擎快捷跳转</h3><p>这是个油猴脚本<a href="https://link.segmentfault.com/?enc=KLlJtaTtHJzJKzykkFHArw%3D%3D.d5RdSmeaPeBTbhpA%2Bi3UMt4CZmn4%2Bm2cQY5GU1ZekEDg7RI2YVOAGhU6JHCMEnHZxiTujFNtqFd6ca6jeM6SPw%3D%3D" rel="nofollow">https://greasyfork.org/zh-CN/...</a> ,可以<br>方便的在各个搜索引擎之间跳转,增加可视化设置菜单,能更友好的自定义设置,修复百度搜索样式丢失的问题。</p><p>关于油猴脚本之前介绍过很多次了,公众号后台回复 <code>油猴</code> 获取,安装详情见文章<a href="https://link.segmentfault.com/?enc=Lbr7Ycmtt8eVrob3DLLZkg%3D%3D.u8PbLWpZlorMC7byRk3QoXP6e2ZzrMCHlxmjDOGTvMIbXzWjuA4rbTuA8mSFM3Dd69y9u1BlnGP9FGpveSal0A%3D%3D" rel="nofollow">实用油猴脚本推荐,让你的谷歌浏览器更强大</a></p><p>搜索框下方列出了网页,翻译,知识,图片,视频,音乐,社交,购物等搜索网站快捷方式,可以直接进入这些网站搜索对应关键词。<br> <img src="/img/remote/1460000025183953" alt="image.png" title="image.png"><br>对百度搜索同样有效。<br><img src="/img/remote/1460000025183954" alt="image.png" title="image.png"></p><p>网址还可以自定义。<br><img src="/img/remote/1460000025183959" alt="image.png" title="image.png"></p><h3>搜索黑名单</h3><p>有时候不想在搜索结果看到某些网站,可以安装搜索过滤扩展 uBlacklist <a href="https://link.segmentfault.com/?enc=KLNzdeaEai9qaotXhuxXVQ%3D%3D.BnvNJJALDBUMWxDwFeCF%2ByxiMvO8VxIA0bPF5EoooQw1iUMBkb9R9eecsZ62Pwe2ungeLsgVPY2z14bJtYBwu5F1PZl8tDocyiiHHn2foXOphsy%2FmtCwp%2B38BEqPxi34" rel="nofollow">https://chrome.google.com/web...</a> ,方便你搜索的时候不看某些垃圾网站的搜索结果。</p><p><img src="/img/remote/1460000025183960" alt="image.png" title="image.png"><br>对于某些专门采集数据的垃圾网站,推荐安装扩展终结内容农场 <a href="https://link.segmentfault.com/?enc=tiPVnJGFFp%2F4AZhEa99RTw%3D%3D.YKYF%2BHipmU0W%2FZU4VSnsZAdLZ5Q%2BRArn5AJGxVHPgp1o9w0sw9sJyE8SoRUxX%2BKigmCEsPVVXF3CCKe0rzziaIqFo7D8F4%2B4%2FezDkoCPG%2F80mjZmGBQMb8zOQGpbZybYgjGcsV6ZsIcTYdeaudqTIw%3D%3D" rel="nofollow">https://chrome.google.com/web...</a> ,在搜索结果会有标识 <br><img src="/img/remote/1460000025183957" alt="image.png" title="image.png"><br>打开后会有提示。<br><img src="/img/remote/1460000025183962" alt="image.png" title="image.png"></p><h3>右键搜</h3><p>一个优秀的右键菜单 Chrome 扩展程序(公众号后台回复 <code>谷歌</code> 获取) <a href="https://link.segmentfault.com/?enc=AySro62Qej5PrysMSS%2BF4A%3D%3D.bPp2heRlsX01t0LV8CtAFyLMXO5nqbiY6LXil6Sd3xi6itNpTgZpgsTdDjJAi6oC" rel="nofollow">https://github.com/xuender/cm...</a> ,右键菜单增加了跳转扩展程序,书签管理,插件,创建短网址,生成二维码等功能。<br><img src="/img/remote/1460000025183963" alt="image.png" title="image.png"><br>菜单可以自定义。<br><img src="/img/remote/1460000025183964" alt="image.png" title="image.png"></p><h3>搜索技巧</h3><p>用<code>《》</code>来搜索书籍或者电影,比如 《明朝那些事儿》,如果搜电子书在书名关键词后加上文件格式,如 pdf/epub/mobi/azw3/txt等 比如 <code>明朝那些事儿 filetype:pdf </code>或者 <code>明朝那些事儿 inurl:pdf</code>,搜出的结果都是PDF文件。<br><img src="/img/remote/1460000025183955" alt="image.png" title="image.png"></p><p>site 站点搜索,比如在b站搜索 周杰伦 <code>site:bilibili.com 周杰伦</code>,百度搜索工具里可以直接输入站点搜索,类似的语法还有查询天气 weather: 北京,查询股票stocks: 微博,查询地图map: 北京,查询电影movie: 夺冠,查询新闻源source: 国庆放假安排 。<br><img src="/img/remote/1460000025183956" alt="image.png" title="image.png"></p><p>数字间隔搜索,比如2000年到2010年的奥斯卡 <code>奥斯卡 2000...2010</code><br><img src="/img/remote/1460000025183968" alt="image.png" title="image.png"><br>模糊搜索,比如想找一首歌,只记得歌词里的几个字,搜索 <code>*爱你很久</code>很轻易的找到周杰伦的《晴天》。<br><img src="/img/remote/1460000025183967" alt="image.png" title="image.png"></p><p>搜索允许目录浏览的网站,比如 <code>index of 电影</code>可以搜到很多人的私人网盘。<br><img src="/img/remote/1460000025183969" alt="image.png" title="image.png"><br>这个告诫我们千万别把自己的私人网盘放公网,万一放了某些不可描述的东西。<br><img src="/img/remote/1460000025183970" alt="image.png" title="image.png"></p><p>更多谷歌浏览器的实用技巧见之前文章 <a href="https://link.segmentfault.com/?enc=r6wnz52GsR9iM9GeGp3Oew%3D%3D.E7eWTxaXjd2lXcJ9Cqnhds2uBqb6i5%2FcyvHWHTadA2uPQSCD%2FLT0MfIvyx9vOhYoomxw2BbSFka1pc3e9i6fhw%3D%3D" rel="nofollow">那些你可能不知道的谷歌浏览器实用技巧</a> </p><p><img src="/img/remote/1460000025183965" alt="免费知识星球,每天更新" title="免费知识星球,每天更新"></p><h3>公众号 苏生不惑</h3><p><img src="/img/remote/1460000025183966" alt="扫描二维码关注或搜索微信susheng_buhuo" title="扫描二维码关注或搜索微信susheng_buhuo"></p>
Python 生成你的朋友圈九宫格图片
https://segmentfault.com/a/1190000025127287
2020-09-25T21:56:13+08:00
2020-09-25T21:56:13+08:00
苏生不惑
https://segmentfault.com/u/sushengbuhuo
3
<p>关于微信之前写过以下文章,有兴趣可以点击查看:</p><p><a href="https://link.segmentfault.com/?enc=UREMY0%2F2hYNedDQbu4PTkg%3D%3D.mf9Ju98ifMwveBwRx6N2Wg7gMWZf7LkZ876ImpOUbqYsiwRkiPXi2F3KWtKOkA1aS83jrZO9axrha%2Fa4VmR2AA%3D%3D" rel="nofollow">如何导出你的微信语音</a></p><p><a href="https://link.segmentfault.com/?enc=%2Fm4fxCFQV5%2BX8wuuT25T0w%3D%3D.M03S7D2MQ56BKrgPs%2BTrt%2Ft67AqZnjGqGaOdmxCtoy4qWM8n1vGz3X8Lx8Qe3XGl50IQnKGbjTJ4mbaNnyFg9g%3D%3D" rel="nofollow">c 盘空间又满了?微信清理神器帮你释放空间</a></p><p><a href="https://link.segmentfault.com/?enc=ccxIDncw6W9Taz41v2yGGQ%3D%3D.xpT8lcsqWGi0YfMd%2BvIFFI0QeYYXC6gDkG8mBvz1YMWtBOb6M1Iyz1JB4pXS5biKtjDvhqoJEriRH7FmsC3t3w%3D%3D" rel="nofollow">微信撤回的消息也能看到!</a></p><p><a href="https://link.segmentfault.com/?enc=2ZWwy10s90w3%2BhQHO4i3bA%3D%3D.o2pjn1MY79wO4yaqD2NrIDUhbtn4u34EHTWp%2FcE10nhxYkBL9skEj9YAx%2Fh82c1xOn16wfo3n2FNRnDuEcme3A%3D%3D" rel="nofollow">如何备份可能被删的公众号文章和网页</a></p><p><a href="https://link.segmentfault.com/?enc=wCBLXhqLCsXZHW3ohopDlQ%3D%3D.xxuh%2BgnNQNE%2FL2cAF0%2FJgAgYA5twW%2F1tA6F7ZTjrpGjSDEEizWDLV5IjSNxriUSf5AAHaVHNJsTFbGcFmbl8Jw%3D%3D" rel="nofollow">如何在电脑上登陆多个微信</a></p><p><a href="https://link.segmentfault.com/?enc=Cko8LSwsEPVwrl0vkEsGCw%3D%3D.psr%2B23NbG9aTPhZ5uesbiNNjt3cDoW%2BeLpvEbuM%2ByTp%2FrRJ%2BhqLutE%2B4iexWmhThxAUSyUQhlbouY5WG6k5%2BwA%3D%3D" rel="nofollow">如何发一条空白的朋友圈</a></p><p><a href="https://link.segmentfault.com/?enc=3p9Yr45OBxjtHNB9PDI7rQ%3D%3D.7A6hHnWLMToz%2BPHZ7QrVga391myUO5KiNXU1lg2jTkGEWs6p0NZdP04FAqiBi4nHbrW3m5AhGcYLL%2B1%2B0abAbg%3D%3D" rel="nofollow">那些你可能不知道的微信奇技淫巧</a></p><p><a href="https://link.segmentfault.com/?enc=rRQcSMuWmaZZGuRlzDJhlA%3D%3D.WDL2l3GUHqd3OARv5kESORKD4pWCL835PfrzbMbd0zrYwD1l09DKEs6CFMbxY%2Bnao8BPJscKuyAPbOx3CpTZCQ%3D%3D" rel="nofollow">一键生成你的微信社交数据报告</a> </p><p>你可能在朋友圈看过九宫格图片(把一张图片按照比例分成九份),就像这样的:<br><img src="//p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/0fd231a5ab354a559047cd81f552af47~tplv-k3u1fbpfcp-zoom-1.image" alt="image.png" title="image.png"><br>还有微博九宫格图 <a href="https://link.segmentfault.com/?enc=2Ws9UsrR1x9vGvcEuHZLYg%3D%3D.BmODZbEUZa8wWrk4vxKotmVqdk6ZrezsCs0cOx18zx2%2BhB3o2CZz%2Fkel4UnifUmr" rel="nofollow">https://weibo.com/2717930601/...</a> :<br><img src="//p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/c668c958ff224b099f50f49e995a1d34~tplv-k3u1fbpfcp-zoom-1.image" alt="image.png" title="image.png"></p><p>这种九宫格图片怎么发的呢?下面用Python搞定它,Python是门很简单实用的语言,即使不做开发工作也可以学习下,比如之前的下载抖音 <a href="https://link.segmentfault.com/?enc=j31p74E7IwVuCD4NZ994Fw%3D%3D.PcvoK%2F5FKe6nYapCxaBAw5pdl31j7AIfNbzaMT4r5Ika2WO55BdaCU3XHpAUwO95NbwhkX0hyPA1ZIxyrqJ9Vw%3D%3D" rel="nofollow">一键批量下载抖音无水印视频</a> ,下载公众号文章<a href="https://link.segmentfault.com/?enc=c%2FEp7n5PI9HZaSvJeiSLzA%3D%3D.BOPjFrP3sDYfoTVV5t9X4k0KKb8VT0oH8%2FbF56yLD5s1gj04DOjn%2BtiaJaDe5%2BawrFDBFavY2kSyd6uLv5TatA%3D%3D" rel="nofollow">一键下载公众号所有文章,导出文件支持PDF,HTML,Markdown,Excel,chm等格式</a> 都是用的Python,之后我会写一篇如何使用Python来抓取数据,代码非常简单,只要你认识英文字母就会用。</p><h3>PIL处理图片</h3><p>先用pip安装切割图片的库 PIL <code>pip install Pillow</code> , 然后编辑代码:</p><pre><code class="js">from PIL import Image,ImageSequence,ImageFilter
pic = input("请输入图片文件名:")
im = Image.open(pic)
width = im.size[0]//3
height = im.size[1]//3
x = 0
y = 0
filename = 1#保存的文件名
for i in range(3):
for j in range(3):
crop = im.crop((x, y, x+width, y+height))
crop.save(str(filename) + '.jpg')
x += width
filename += 1
x = 0
y += height</code></pre><p>直接命令行执行 python pic.py ,输入图片文件名即可在本地生成9张小图。<br><img src="//p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/958dfd8a4bf14e13bafb3d28521fce35~tplv-k3u1fbpfcp-zoom-1.image" alt="image.png" title="image.png"></p><p>还可以将代码打包为exe可执行文件,这样不用安装Python就可以运行了。</p><h3>pyinstaller 打包exe</h3><p>打包用的工具是pyinstaller,先<code>pip install pyinstaller</code>安装它,然后<code>pyinstaller -F pic.py </code>,不过我运行的时候出错了。<br><img src="//p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/262974b02c16408bb44b5dc53c4c67cd~tplv-k3u1fbpfcp-zoom-1.image" alt="image.png" title="image.png"></p><pre><code class="js">
for real_module_name, six_module_name in real_to_six_module_name.items():
AttributeError: 'str' object has no attribute 'items'</code></pre><p>谷歌了下需要升级库。</p><pre><code class="js">λ pip install -U setuptools
Collecting setuptools
Downloading https://files.pythonhosted.org/packages/6d/ed/52e05469314a266f68d9f251a8c1ab7a21a03327b1724056e3eea654bfd1/setuptools-50.0.3-py3-none-any.whl (784kB)
Installing collected packages: setuptools
Found existing installation: setuptools 41.2.0
Uninstalling setuptools-41.2.0:
Successfully uninstalled setuptools-41.2.0
Successfully installed setuptools-50.0.3
pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple
# 更新pip版本
python -m pip install -U pip
λ pip uninstall enum34
Uninstalling enum34-1.1.6:
Would remove:
d:\python\lib\site-packages\enum34-1.1.6.dist-info\*
d:\python\lib\site-packages\enum\*
Proceed (y/n)? y
Successfully uninstalled enum34-1.1.6
"""
</code></pre><p>再次执行<code>pyinstaller -F pic.py</code> 终于成功了,不过生成的exe文件有点大(20多MB,公众号后台回复 <code>朋友圈</code> 获取exe文件),双击exe文件输入文件名就可以运行了。 <a href="https://link.segmentfault.com/?enc=XEwxwvvR4eLcDiKDggts5A%3D%3D.HRSM%2FXSCG78LLiBOfigSy%2FvDV8uAr3OCk9FiJul9JIuVAcFoUE2Rcng6lAKCQ7WC" rel="nofollow">https://www.lanzoux.com/iWtJN...</a></p><pre><code class="js">60106 INFO: Building PKG (CArchive) PKG-00.pkg completed successfully.
60112 INFO: Bootloader d:\python\lib\site-packages\PyInstaller\bootloader\Windows-32bit\run.exe
60114 INFO: checking EXE
60115 INFO: Building EXE because EXE-00.toc is non existent
60115 INFO: Building EXE from EXE-00.toc
60115 INFO: Appending archive to EXE d:\download\dist\pic.exe
60279 INFO: Building EXE from EXE-00.toc completed successfully.</code></pre><p><img src="//p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/a66756e0851741ee80be9db76520ee27~tplv-k3u1fbpfcp-zoom-1.image" alt="image.png" title="image.png"></p><p>PIL除了切割图片还可以对照片去色。</p><pre><code class="js">img = Image.open("jay.jpg")
img2 = img.convert("L")
img2.save("jay2.jpg")</code></pre><p>去色效果图:<br><img src="//p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/90d2d0b2f4b24c559e9530862e7fd3c1~tplv-k3u1fbpfcp-zoom-1.image" alt="mm2.jpg" title="mm2.jpg"></p><p>对照片旋转90度。</p><pre><code class="js">img3 = img.rotate(90)
img3.save("jay_rotate.jpg")</code></pre><p>旋转效果图:<br><img src="//p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/4f2f73630ab94428b0cd4a3355811285~tplv-k3u1fbpfcp-zoom-1.image" alt="img_rotate.jpg" title="img_rotate.jpg"></p><p>对照片翻转。</p><pre><code class="js">img4 = img.transpose(Image.FLIP_LEFT_RIGHT)
img4.save("jay_transpose.jpg")</code></pre><p>翻转效果图,周杰伦七里香几个字翻过来了:<br><img src="//p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/5fe135e7e6b5424a97b6075dd645ab44~tplv-k3u1fbpfcp-zoom-1.image" alt="img_transpose.jpg" title="img_transpose.jpg"></p><p>除了使用Python 也有在线工具和微信小程序可以生成九宫格图片 <a href="https://link.segmentfault.com/?enc=nLQrNLiEHI31MISLaL4y8g%3D%3D.2yFx9wrKp%2Bs40ksyTvPna%2ByUlTuQdoI8YWWmNSeEtwU%3D" rel="nofollow">https://www.dute.org/image-clip</a> ,上传图片下载即可。<br><img src="//p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/b74b2077d67a46389d710d782d4c9400~tplv-k3u1fbpfcp-zoom-1.image" alt="image.png" title="image.png"></p><p><img src="//p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/3081aba52ee34a259591a9a448f43f4c~tplv-k3u1fbpfcp-zoom-1.image" alt="免费知识星球,每天更新" title="免费知识星球,每天更新"></p><h3>公众号 苏生不惑</h3><p><img src="//p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/9210787500514fd99720b5be974482ae~tplv-k3u1fbpfcp-zoom-1.image" alt="扫描二维码关注或搜索微信susheng_buhuo" title="扫描二维码关注或搜索微信susheng_buhuo"></p>
Python 一键批量下载抖音无水印视频
https://segmentfault.com/a/1190000025127225
2020-09-25T21:50:59+08:00
2020-09-25T21:50:59+08:00
苏生不惑
https://segmentfault.com/u/sushengbuhuo
11
<p>关于下载视频之前写过 <a href="https://link.segmentfault.com/?enc=t%2BESZ6teD%2Ben%2B9R9OedPbw%3D%3D.dUu5eXNJ%2FcykdnFqUv%2FXUt%2B9onKdsHDcXLbbQ%2BFkg%2FDoWDMaF%2BUaLpxjGeQx5XwdonDUlA050Zb1MrLm%2BrhF0A%3D%3D" rel="nofollow">如何轻松下载腾讯/微博/优酷/爱奇艺/b站等全网视频? </a> , <a href="https://link.segmentfault.com/?enc=djVKHnhMDcP6VOwZfGQkmg%3D%3D.Qq6f0NsHZ4%2BBb%2BWEYbw%2BI3L42VrG81sCRonBfdEtjbynSfU8rv6eHKTiBGcKP9mUgvzRsxQ%2Bxeph0tO1bVLcLQ%3D%3D" rel="nofollow">那些你可能不知道的视频下载奇技淫巧</a></p><p>抖音视频也可以直接通过idm来下载,先在抖音复制视频链接。</p><p><img src="/img/remote/1460000025127228" alt="image.png" title="image.png"><br>用谷歌浏览器打开视频链接后点击视频右上角的idm(公众号后台回复 <code>idm</code>获取软件 )就能下载了 。<br><img src="/img/remote/1460000025127229" alt="image.png" title="image.png"></p><p>不过这样下载的视频带有抖音的标志,如果想去除这个水印,下面分享个简单的方法。<br><img src="/img/remote/1460000025127231" alt="image.png" title="image.png"></p><p>打开浏览器控制台使用手机模式访问会跳转到 <a href="https://link.segmentfault.com/?enc=YAhoQmbtwr1t0TMLLJepiQ%3D%3D.ILsUo%2BV6FTT1QqMFklisZNFbyb%2BdgXxeVdPuQwko4XLsjvN2uIDrMULjWYjU0MQSXiPf3LdzyGoZphGJXEcM2w%3D%3D" rel="nofollow">https://www.iesdouyin.com/sha...</a> <br><img src="/img/remote/1460000025127230" alt="image.png" title="image.png"></p><p>可以看到请求接口 <a href="https://link.segmentfault.com/?enc=OgC%2B2QtfydzQPeuNdpSZqw%3D%3D.pYtNCrwtNSyF6Ylcz3aAWvnevrNG6R4E4YTSivhEF6uFJymA7VaAREON5dmW%2FGpWfXtkW%2BQTksLQE1pbASDXv6zN2hDwa3EvfaQXfParLNaHUzrFinqEyF2F76nuPoum" rel="nofollow">https://www.iesdouyin.com/web...</a> ,返回值play_addr里就有播放地址url_list <a href="https://link.segmentfault.com/?enc=WF78M368WSoAR9QPOeK6oQ%3D%3D.cy3%2FY9k%2BI21AipMVNDKNHCAv0Zo1pleqLXXGIESMGmbETEvo921i%2BBE%2BJIuxUJZzDTjYWD8d8z8EpEwuRtEuOXKuKNUFAFZHOHLsbPRVPztzg1jQsrwgl8Fpc6qdpkTfjp9Xsen9xCK90L3ZtI69xw%3D%3D" rel="nofollow">https://aweme.snssdk.com/awem...</a><br>这个地址是有水印的,将地址里的playwm改为play就是无水印播放地址了。</p><p>下载后播放对比下,左侧的抖音水印没了。<br><img src="/img/remote/1460000025127233" alt="image.png" title="image.png"><br>无水印视频还少了3秒 ,因为视频结尾的一小段 <code>来抖音,发现更多创作者</code> 也没了。<br><img src="/img/remote/1460000025127232" alt="image.png" title="image.png"></p><p>当然这样下载无水印视频有点麻烦,一般小白还不会,Python 可以帮你一键下载。</p><pre><code class="js">
url = input("请输入你要去水印的抖音短视频链接:")
response = requests.get('https://www.iesdouyin.com/web/api/v2/aweme/iteminfo/?item_ids='+str(vid))
result = response.json()
#print(result)
item = result.get("item_list")[0]
author = item.get("author").get("nickname")
mp4 = item.get("video").get("play_addr").get("url_list")[0]
with open(desc+".mp4", 'wb') as f, open(desc+".mp3", 'wb') as f2:
f.write(video.content)
f.close()
f2.write(audio.content)
f2.close()
print("===>音频和视频下载完成")
</code></pre><p>直接执行脚本 python douyin.py ,很快下载好了。<br> <img src="/img/remote/1460000025127234" alt="image.png" title="image.png"></p><p>视频对应的mp3音频也下载了。<br><img src="/img/remote/1460000025127235" alt="image.png" title="image.png"></p><p>除了Python已经有很多不错的软件可以很方便的下载无水印抖音视频了,下面分享几个好用的。</p><p>这个软件(公众号后台回复 <code>抖音 </code>获取软件) 支持抖音,皮皮虾,快手,火山,微视等平台视频的批量下载,还支持采集视频。<br><img src="/img/remote/1460000025127236" alt="image.png" title="image.png"></p><p><img src="/img/remote/1460000025127237" alt="image.png" title="image.png"><br>输入抖音视频链接地址 <a href="https://link.segmentfault.com/?enc=%2FM3D9Q6mJjQ1B6Rf1xG2WA%3D%3D.2skMAMGH2gW00D0GuH6EigXjaWV3LerhINwOyWvaAtg%3D" rel="nofollow">https://v.douyin.com/JkaChFt/</a> ,点击解析可以看到视频标题和下载链接。<br><img src="/img/remote/1460000025127238" alt="image.png" title="image.png"><br>还可以输入抖音作者主页地址 <a href="https://link.segmentfault.com/?enc=tsx11JNBaLMB3DNjFBnPfA%3D%3D.%2FIIXTh5Ghely3qafFu7fQFN35kuM7zQ27RyNN%2FdK%2F6Q%3D" rel="nofollow">https://v.douyin.com/JkaaoTH/</a> ,解析可以获取作者视频列表。<br><img src="/img/remote/1460000025127239" alt="image.png" title="image.png"><br>然后右键下载,很快下载完了。<br><img src="/img/remote/1460000025127240" alt="image.png" title="image.png"><br>播放看看,左上方的抖音水印没了。<br><img src="/img/remote/1460000025127241" alt="image.png" title="image.png"></p><p>另外一个软件 抖音信息解读 ,可以搜索列出作者600多个视频(包含作者头像,视频标题,视频地址,点赞数,评论数,分享数,音乐地址,无水印链接等),在右侧可以选择视频下载。<br><img src="/img/remote/1460000025127242" alt="image.png" title="image.png"><br><img src="/img/remote/1460000025127243" alt="image.png" title="image.png"></p><p><img src="/img/remote/1460000025127244" alt="免费知识星球,每天更新" title="免费知识星球,每天更新"></p><h3>公众号 苏生不惑</h3><p><img src="/img/remote/1460000019152534" alt="扫描二维码关注或搜索微信susheng_buhuo" title="扫描二维码关注或搜索微信susheng_buhuo"></p>
王菲k歌又上微博热搜,Python分析下微博网友评论
https://segmentfault.com/a/1190000025127104
2020-09-25T21:35:42+08:00
2020-09-25T21:35:42+08:00
苏生不惑
https://segmentfault.com/u/sushengbuhuo
2
<p>最近<code>王菲状态</code>话题上了微博热搜 <a href="https://link.segmentfault.com/?enc=BoprnOolMqIvA%2BCzCyS1zA%3D%3D.gonv5tjPzTa1Z4J00KAiH%2BQTvRvB5sz7Dwo%2BUi9sggN1a4FVtW8uZKy9VfSUskXk" rel="nofollow">https://weibo.com/1266269835/...</a> <a href="https://link.segmentfault.com/?enc=iG98FfiqQNgdTauwJ24s0A%3D%3D.8v5MbbT5zIvfJekbFI09SiTEbh3V7oxwRaE1fBQ1fnT6BH%2F%2FKhhEkjk1J3p8rg79" rel="nofollow">https://weibo.com/6598655984/...</a> <br><img src="/img/remote/1460000025127107" alt="image.png" title="image.png"></p><p><img src="/img/remote/1460000025127108" alt="image.png" title="image.png"><br>还和马云合唱了 <code>如果云知道</code> <a href="https://link.segmentfault.com/?enc=3Mr2XKCdmXaOUqpiwKLKQg%3D%3D.Re%2BAJiBLU9SEpAnh3xDhJ7iDwN6ienmbyI8KBYHqbC%2BOJKCi8lO292ofwn2mbRi2" rel="nofollow">https://weibo.com/1956700750/...</a> <br><img src="/img/remote/1460000025127110" alt="image.png" title="image.png"></p><p>5年不更新的微博下评论开始求开演唱会 <a href="https://link.segmentfault.com/?enc=CJA81L1Oc5ootJvH4CE75Q%3D%3D.gLndw7KTcpe39x%2FTE7%2FIKSjkisZvgWcxaadv%2FcC96eoYyExZFTlNFdcxsLE4u2WU" rel="nofollow">https://weibo.com/1629810574/...</a> </p><p><img src="/img/remote/1460000025127109" alt="image.png" title="image.png"></p><p><img src="/img/remote/1460000025127112" alt="微博评论.png" title="微博评论.png"></p><p>于是用Python抓取了下这条微博下的评论(前几十页评论),微博有4个域名: 网页版weibo.com ,手机端 m.weibo.com,移动端weibo.cn ,h5端 m.weibo.cn ,这里用网页版为例,打开控制台可以抓取到评论接口<br><a href="https://link.segmentfault.com/?enc=es699JZWLtOQUgHEFTzTLA%3D%3D.26OIoyYK0hwGBfnAUQmpVPZW1zPVkzs7eQPCFznRhXmg7Ry9U72ynsILsRVlq%2FXbZeKLQ4jUschSkEmxdTvpsbzLwnFyFHYHe3w0Gb4Da6A%3D" rel="nofollow">https://weibo.com/aj/v6/comme...</a> </p><p><img src="/img/remote/1460000025127111" alt="image.png" title="image.png"></p><p>同样的移动端 <a href="https://link.segmentfault.com/?enc=pYPEevZKZcAXf%2Fv6gnNtng%3D%3D.dq2xWGTecrwe9MfKS5uzd9I5%2Fb4fPuUBgjqQ1M47a0ATP5BzhhwvMxxFsdsLoBeq" rel="nofollow">https://weibo.cn/search/?tf=5...</a> 搜王菲可以找到这条微博<a href="https://link.segmentfault.com/?enc=77%2Fyh2ELdoxZsf%2BsfV2YsA%3D%3D.GtMgtF7pGhkI38%2Bf2xiscF%2FfIGC7kTPksePvQkK%2FujKf45kHW4R%2FkcaHwY9tlRrF" rel="nofollow">https://weibo.cn/comment/C8Fq...</a> ,评论也在一块。<br><img src="/img/remote/1460000025127114" alt="image.png" title="image.png"></p><p>还有h5端 <a href="https://link.segmentfault.com/?enc=y2965NDyWYeh8QYlkyDcwA%3D%3D.VElhrGrJvzb74hCDO%2FJK5Ygd%2FuEGAwd0Ta6YuCu85ncPz0f%2Bmhq4FlumFhQWEcr8" rel="nofollow">https://m.weibo.cn/detail/382...</a> 抓取到接口<a href="https://link.segmentfault.com/?enc=Gusx3%2B02jynGI3m4uBBwcg%3D%3D.cY%2FNkzhHUzfPZWz6OvjoZAwO%2FEKq5lGtmiGtsPc2QEMijMWmiMoAh%2B4HJqzoQfatPfSniwDG9LfhivG5eY3G0fbSg3xa3SGOI4vIZd7IoeyGwbB9Ey2RoC%2FI7Fa6o3bmBIS2n5L68ypnBRwtXDN6QK4JXZ9F2mj%2FcK60TuIklvE%3D" rel="nofollow">https://m.weibo.cn/comments/h...</a></p><p>有了接口地址,数据就很好抓取了,这里写入文件。</p><p><img src="/img/remote/1460000025127113" alt="image.png" title="image.png"><br>然后用wordcloud对微博评论生成词云图,主要关键词是好听,菲姐,演唱会,真的很期待王菲再开演唱会。<br> <img src="/img/remote/1460000025127115" alt="image.png" title="image.png"><br>也可以通过网站 <a href="https://link.segmentfault.com/?enc=Hgl7g7d1Oxe998QMW7%2BdAA%3D%3D.qKVrJkRDwSZhVzR%2Bk%2B08Btl4eYgytQLcqx8Spni2LyM%3D" rel="nofollow">http://cloud.niucodata.com/</a> 生成,上传文字即可。<br><img src="/img/remote/1460000025127116" alt="image.png" title="image.png"></p><p>另外我用Chrome扩展备份了王菲1500多条微博,详情见之前文章<a href="https://link.segmentfault.com/?enc=pPFcLREqzDCsKuq4KyW3Lw%3D%3D.64qotQhuE8SAjzugAJbEj%2Bb5CwSdGD9dRmqqeb4aBIK6xpgRyrMEcqDKaX4umPkCy4bplGiE124xo6KoIZG6JQ%3D%3D" rel="nofollow">用Chrome扩展一键备份微博</a> <br><img src="/img/remote/1460000025127117" alt="image.png" title="image.png"><br>如果需要备份文件在公众号后台回复 <code>微博</code> 获取 <br><img src="/img/remote/1460000025127118" alt="image.png" title="image.png"></p><p>天后已经很久不出专辑了,自从去年发了一首单曲《我和我的祖国》快过去一年了,不过即使20年前的歌今天依然在传唱 <a href="https://link.segmentfault.com/?enc=DZ1Bg%2F1JVH4LRbto7XLsQg%3D%3D.tZu8RtwuBie1qYPhDzKNEZSFr4bQ%2Bw8cl9m1fHnqgSfrrusz1QZy82MlTSF81cjy92j888uo%2BSiHRoT7ysgKew%3D%3D" rel="nofollow">王菲51岁:爱她,不只是因为她的歌</a>,比如《红豆》<br><a href="https://link.segmentfault.com/?enc=jWa19q7c26HNqUdtw2M8QA%3D%3D.fJ7Uw1RMs9bHcwv%2BHECk6V8PIHK27easFThPOYEfPaHNn4j7%2Fp76i%2F9%2B7vv7bb%2BU" rel="nofollow">https://music.163.com/#/song?...</a>,可惜目前在网易云音乐需要VIP才能听,如果不想花钱看看之前文章<a href="https://link.segmentfault.com/?enc=DL6a6mv6s%2BgqVTyOITQl3Q%3D%3D.F3MOIn6hfFcI%2FC0TwAzEZETrT69CrnxQcJCojQEqWvOwERix4NvWIoDlG646rY%2BG6i7S%2FlHEETwSc0MQj%2Bcppw%3D%3D" rel="nofollow">一键解锁网易云音乐变灰歌曲</a> <br><img src="/img/remote/1460000025127119" alt="image.png" title="image.png"><br>这里抓取前200页的评论生成词云图,我也很喜欢这首歌。 评论接口地址<a href="https://link.segmentfault.com/?enc=S2QrOInbU2vWiYYd8FQFDQ%3D%3D.6omKiA6Ujz7TqnEGFX5HnbcrcmzSFFcLl6%2FMUL3oJjXocfJgBJntn1%2B5tFBAwZUc73d6A0f0cSPSQRdHr3mDGnyDWmFZE3HQsFE7DAI0cUdp9bY6s5sEeaYMkq18Bvty" rel="nofollow">http://music.163.com/api/v1/r...</a> <br><img src="/img/remote/1460000025127120" alt="image.png" title="image.png"></p><h3>公众号 苏生不惑</h3><p><img src="/img/remote/1460000019152534" alt="扫描二维码关注或搜索微信susheng_buhuo" title="扫描二维码关注或搜索微信susheng_buhuo"></p>
2019 年如何优雅的上谷歌
https://segmentfault.com/a/1190000020863765
2019-10-30T21:29:02+08:00
2019-10-30T21:29:02+08:00
苏生不惑
https://segmentfault.com/u/sushengbuhuo
19
<p>国内有百度搜狗bing等搜索引擎,为什么还推荐谷歌呢?平常自己对比下搜索结果就知道,其他就不多说了。<br><img src="/img/remote/1460000020863768" alt="image.png" title="image.png"></p>
<p><img src="/img/remote/1460000020863769" alt="image.png" title="image.png"></p>
<p>之前我在<a href="https://link.segmentfault.com/?enc=zVXBbK0j32qiEEgD%2BqxXPw%3D%3D.mXAiksIyW2pZCGFzl3Rrbgh31EvPwxrBbqU2q2bvXUQ%3D" rel="nofollow">知识星球</a>上发了个动态.</p>
<blockquote>Google 搜索英文单词发音,比如 pronounce love ,搜索结果提供美式和英式两种发音,还可以调整语速。</blockquote>
<p><img src="/img/remote/1460000020863770" alt="image.png" title="image.png"></p>
<p><img src="/img/remote/1460000020863771" alt="image.png" title="image.png"></p>
<p>还有更多搜索技巧可以看之前的文章 <a href="https://link.segmentfault.com/?enc=naW3yRUls2HSF1JieUc0Zw%3D%3D.3mGw8WhQrvBt4fRSYuQ8oARdK1isO%2BQ5giV67UGF4dysBaE2YbKH6m0xCOITU57zh1QlHjf5eexIEa8LdeeHfA%3D%3D" rel="nofollow">那些你可能不知道的搜索奇技淫巧</a>,有小伙伴想知道怎么上谷歌,于是花点时间整理了下面几个上谷歌的方法,如果有帮助还请大家点个在看支持下。</p>
<h3>修改hosts</h3>
<p>就是通过修改hosts文件来访问谷歌,windows 的hosts文件在<code>C:\WINDOWS\system32\drivers\etc</code> ,其他系统在<code>/etc/hosts</code>添加<code>https://raw.githubusercontent.com/googlehosts/hosts/master/hosts-files/hosts</code><br>这个文件的内容到hosts文件就行了,如果提示修改没有权限,右键hosts文件属性-安全-选择当前用户名点击编辑,勾选所有权限。<br><img src="/img/remote/1460000020863772" alt="image.png" title="image.png"></p>
<p>不过这种方法不稳定,有些地区还上不了。</p>
<p>ps:如果在双11把你女朋友电脑的hosts加上<code>127.0.0.1 www.taobao.com</code> ,电脑就没办法上淘宝买买买了,不过小心被分手的后果。。。<br><img src="/img/remote/1460000020863773" alt="image.png" title="image.png"></p>
<h3>谷歌镜像</h3>
<p>Google镜像就是一个代理访问谷歌的网站,比如 <a href="https://link.segmentfault.com/?enc=PY4F3OQJ%2BzXtYIBJZCpvSQ%3D%3D.FftjVTq4EflEAVL%2Bg2cNnMgU8cWx037bmC%2BTzTjMDoQ%3D" rel="nofollow">http://ac.scmor.com/</a> http://gs.yovisun.com/ <a href="https://link.segmentfault.com/?enc=3A2DmuPw4u8iGvSZUQQWMA%3D%3D.ygAl%2F3Xik%2BW7Ler58koH5VFkN7SEJiRDsFUsmyHWLU0%3D" rel="nofollow">https://g.zmirrordemo.com/</a> http://scholar.hedasudi.com/ ,这些镜像网站可能随时挂,你可以自己搜索下可用的镜像。<br><img src="/img/remote/1460000020863774" alt="image.png" title="image.png"><br>里面的镜像 4 就能访问Google了,比如这个 <a href="https://link.segmentfault.com/?enc=0bW929F3Q9yIrH0c1GUUuw%3D%3D.4BecBZP%2B%2BIHkJ0V2rjQHCA673DM9XNe7YwL6Dc8Rc4U%3D" rel="nofollow">http://206.189.135.241/</a> <br><img src="/img/remote/1460000020863775" alt="image.png" title="image.png"><br>谷歌学术也有对应的镜像 <a href="https://link.segmentfault.com/?enc=921bSZG9ljI4AM8WMPEWHw%3D%3D.de89IDn2DpY0tD8fRHvQCfYT6Xa8EfmaZ5DBHMVoELg%3D" rel="nofollow">https://xs.glgoo.top/scholar/</a></p>
<h3>Chrome定制版</h3>
<p>这是一个定制版的Chrome浏览器,下载后直接双击<code>一键启动.bat</code>运行,公众号回复 <code>chrome</code> 获取软件。<br><img src="/img/remote/1460000020863776" alt="image.png" title="image.png"><br><img src="/img/remote/1460000020863778" alt="image.png" title="image.png"></p>
<h3>谷歌访问助手</h3>
<p>这是一个Chrome扩展,<a href="https://link.segmentfault.com/?enc=WyLvAjjVAFqgRGsuvilZMg%3D%3D.jUASsnECOEB44Y9tP9vcmucEhbHu%2B%2BFJTbEhUsFdxWWzTYp4m1QnIK8YRG73vHgag%2Fb0DW1RFhgJW26KT8MZezHiq8o3s9aiQyI4c82HFx7UQhVVVCBl4AibDrMdngJiibpM5kxoMisWrcM5CfWAeA%3D%3D" rel="nofollow">https://github.com/haotian-wa...</a>,如果下载很慢或者链接挂了,在公众号回复<code> 谷歌</code> 获取。</p>
<p>下载扩展后打开Chrome浏览器扩展 chrome://extensions/,打开开发者模式,将下载的crx文件拖进去,如果出错提示程序包无效,将crx后缀改为zip再拖进去就能安装成功了,之前讲过安装Chrome扩展油猴,不知道的话再看看之前的文章<br><a href="https://link.segmentfault.com/?enc=ci4WFgseScGGLo9Rcl7KVg%3D%3D.bM7IEFD3bZYv82Gp%2B5vA2WZ4l388LOUFut%2Fjc7%2FvZs77CzZGmqGmwMZVP6TysN8KslhrIvqF6sRjX4RQTajpzg%3D%3D" rel="nofollow">Chrome 浏览器扩展神器油猴</a>,安装完后就能访问谷歌了。<br><img src="/img/remote/1460000020863779" alt="image.png" title="image.png"></p>
<h3>临时方案</h3>
<p>一个临时上谷歌的网站 <a href="https://link.segmentfault.com/?enc=LxifXwqR1PKk61O3JsipJw%3D%3D.8vPLljm5aiqSLVQU9ZbK2apueBH0KKJGLYoGaYVSBC0%3D" rel="nofollow">https://demo.glyptodon.com/</a> 你只有十五分钟的使用时间。<br><img src="/img/remote/1460000020863780" alt="image.png" title="image.png"><br>youtube也可以访问。<br><img src="/img/remote/1460000020863781" alt="image.png" title="image.png"></p>
<p><img src="/img/remote/1460000020863782" alt="image.png" title="image.png"><br>到了时间会自动断开,你需要重新连接,所以只能临时用用。<br><img src="/img/remote/1460000020863783" alt="image.png" title="image.png"></p>
<h3>ssr</h3>
<p>自己搭建 ssr 服务需要一个国外的服务器,网上有很多教程,不过具体操作对普通人还是有点困难,但这种方法好处就是方便在命令行也使用代理。</p>
<p>Git Bash 中用 export <br><code> export http_proxy=10.8.2.2:3128 export https_proxy=10.8.2.2:3128</code><br>或者直接 <code>export ALL_PROXY=10.8.2.2:3128</code></p>
<p>ps:10.8.2.2:3128这个ip我随意写的,并不可用。</p>
<p>然后命令行也可以访问谷歌了。 <br><img src="/img/remote/1460000020863784" alt="image.png" title="image.png"></p>
<p>最后总结下: 修改 hosts 不稳定,经常改文件也麻烦,Chrome 定制版,谷歌镜像和临时方案临时用用可以,自己搭建ssr难度大,谷歌访问助手还算稳定,比较推荐这个。</p>
<p>如果以上都挂了,还可以使用这些小众的搜索引擎 <a href="https://link.segmentfault.com/?enc=NthjH0IzGbg06ebf2Z4Q7w%3D%3D.0m6aqeA7U9Y18VkxHV97ajhcFptpbUvfU1cOQUKtxnA41IR81McSZi6oO9bJGb3ATaz722RIzob5UyuhlCmJfA%3D%3D" rel="nofollow">那些除百度以外你可能不知道的小众搜索引擎</a></p>
<p>推荐阅读:</p>
<p><a href="https://link.segmentfault.com/?enc=H4NtIgE%2FwlvqANHBkM1ouA%3D%3D.zzqvdFHLbpjF%2FuMl%2Bd3zOPfJh7x%2BMX2kUdEZ7IVR0mhxdCf2ntjorIClAg4cvAkxdLruRDJaai5JZma%2BeXlbAw%3D%3D" rel="nofollow">如何发一条空白的朋友圈</a></p>
<p><a href="https://link.segmentfault.com/?enc=ZCyyFOD%2FebKS0J3Ld%2BQFHw%3D%3D.9LfLFzNf1NraaLeBlfmjYb629gXZ56X28hocETCgpfQb05d9HOpsKo%2B4ngxbJdC%2Bwb1QQdBoDWkGVVmG5LFseQ%3D%3D" rel="nofollow">那些在国内还能使用的谷歌产品</a></p>
<p><a href="https://link.segmentfault.com/?enc=een%2BFhhzwxWtWO%2B31yL21g%3D%3D.yq0p%2F%2BfsnyGipD6KKcm%2BgGgWIfM6X5hIFNvixD%2FYi2ppS9Mv5mIQZTbi%2B87DNPBMkkSKgflxxaQyrseOveTXjg%3D%3D" rel="nofollow">那些你可能不知道的微信奇技淫巧</a></p>
<p><a href="https://link.segmentfault.com/?enc=GtLepGT%2FoRjf1yu3rEEuOw%3D%3D.JS0Op0FJfHuX1WNuByPfCsAuuDSm1WySU2EvVLRf4jSj%2F%2FxKoLZ454z6fPSX1TozPjMUk79dbVDv9xJjbYSrfg%3D%3D" rel="nofollow">如何在豆瓣租房小组快速找到满意的房子</a></p>
<p><a href="https://link.segmentfault.com/?enc=ENcUOhtM6AxdIDazN5XnAw%3D%3D.m8EAR3bCRYPlkwjp8EOwfwMrSZVeGlRWcKKpTYAAG7dz5u7Fq21VbYdZF64qXJ%2FjnYsv0qvIx5k1YHXf3fDimw%3D%3D" rel="nofollow">公众号苏生不惑原创文章整理</a></p>
<p><a href="https://link.segmentfault.com/?enc=5KiMXHgEonC1hnSHrO2rHA%3D%3D.rqXtlMRtzkv4AznBwXy1sTtlGvWkSNdooCGQi0lokJbbpM1xpgWw6AXvrcaad0b%2FpyKcN6bSlc6zwVSBtBfjiA%3D%3D" rel="nofollow">Chrome 浏览器扩展神器油猴</a><br><img src="/img/remote/1460000020863785" alt="免费星球" title="免费星球"></p>
<h3>公众号:苏生不惑</h3>
<p><img src="/img/remote/1460000020863786" alt="扫描二维码关注或搜索微信susheng_buhuo" title="扫描二维码关注或搜索微信susheng_buhuo"></p>
那些我常用的 Chrome 扩展神器
https://segmentfault.com/a/1190000020519496
2019-09-28T00:16:29+08:00
2019-09-28T00:16:29+08:00
苏生不惑
https://segmentfault.com/u/sushengbuhuo
20
<p>Chrome仍然是目前最好的浏览器,每天用Chrome 必然少不了使用扩展来增强浏览器的功能,这里整理下我常用的Chrome 扩展。</p>
<h3>油猴</h3>
<p>这个简直神器,所以第一个推荐 <a href="https://link.segmentfault.com/?enc=Iv9olWdASeaRU85hKM8SjQ%3D%3D.waH2vmJ8BXTkoTBfzrGrk73uwjlIrClBTb2K%2B1T1PEM%3D" rel="nofollow">https://www.tampermonkey.net/</a> 下载后在<a href="https://link.segmentfault.com/?enc=KGvwOO%2B5odIU1iInj6tuig%3D%3D.RMIu9t0UTCc5H5Uvihc3n6ei%2Fz0FeWLXCQJfG1AlSc0%3D" rel="nofollow">https://greasyfork.org/zh-CN</a> 这里安装对应的脚本。<br><img src="https://upload-images.jianshu.io/upload_images/17817191-6adf0aadf65e6fbe.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="image.png" title="image.png"></p>
<p>常用的脚本比如百度网盘直链下载<br><img src="https://upload-images.jianshu.io/upload_images/17817191-b7cb5eda1a10d0f7.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="image.png" title="image.png"><br>全网VIP视频免费观看</p>
<p><img src="https://upload-images.jianshu.io/upload_images/17817191-b2f94d4075308365.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="image.png" title="image.png"><br>之前已经写过<br><a href="https://link.segmentfault.com/?enc=FejBEK6sLJBB8G85tKhuvQ%3D%3D.N4YfM9JcQ1LgsRKB9KY3oy4KvxsQ99%2BwvMMk%2F%2Br%2BM%2FL5n%2BpVwSrsiw5QvC8%2F2mjzWilIVZmEJsmsFmR2OWoqvg%3D%3D" rel="nofollow">Chrome 浏览器扩展神器油猴</a><br><a href="https://link.segmentfault.com/?enc=gEJ9cPKtJGGZ7pkD%2BqUH1Q%3D%3D.ow%2F0oUA3rqtoH4Y2oVHRHs%2BADa6UCvR0baLBjeSmOsa099GClNlqAXnbl79kTtH%2FTeg8YMfkhiVO%2B%2BS0tCYQMQ%3D%3D" rel="nofollow">Chrome 浏览器扩展神器暴力猴</a><br>下载地址 <a href="https://link.segmentfault.com/?enc=xXnAs3wdgpjXVPVoJyiFOQ%3D%3D.vJwkpif51GZZOrCeF6ys2oV66A66DVgnCXh0eOXGE4HMtXpdsCBw7d7xMxt%2Bfa6TYsC1KLhvkMDyq77YCwjld7VLAQr7Y4OEPVU9dAqfmLg%3D" rel="nofollow">https://chrome.google.com/web...</a></p>
<h3>取字</h3>
<p>之前写过ocr <a href="https://link.segmentfault.com/?enc=0mtrHgQH69WRRUB93TlasQ%3D%3D.nyNpNvkq49LM4Dx0C04URz8c3JT6wCAvi4GTwXI1YJScnA89ogygwbZDpNgbbHbaUoo4MaWiQlTpagDlvGGbKg%3D%3D" rel="nofollow">那些你可能不知道的 ocr 图片文字识别工具</a>,虽然有桌面版工具天若ocr,但在浏览器里还是用<code>取字</code>这个扩展方便<a href="https://link.segmentfault.com/?enc=px5FIIReYVcTSwQeaQjEsw%3D%3D.TiIbpW016JiUNize89cJgAeNvRx6h99DIRBCP9T8k8%2FIbA9LYeQGYQDxCF%2F7SF%2FX" rel="nofollow">http://willingstudio.com/#ins...</a> ,它具有通识化场景的 OCR 识别功能浏览器插件,快速框选,可精确识别图片或者视频中的文本。</p>
<p>它提供本地安装和Chrome应用商店安装<a href="https://link.segmentfault.com/?enc=jbL3xGKJeDpxhg3Ykf7vOg%3D%3D.ozs3x3S61lwKk9bDfT1nSHlj0Iff4mVjvTmMIjFjjxyMMDfCWMul%2FC3mVaX4Dwsf%2FW05QZUeg2cllx3XGnG8JgrPbDU%2Fe9UaWAnu6i0mPFpRDs2rd6pxRCU%2B0FbBo3Mo" rel="nofollow">https://chrome.google.com/web...</a>://willingstudio.com 安装方法上面也有,上不了Google推荐下面的方法。<br><img src="https://upload-images.jianshu.io/upload_images/17817191-e026322ce645c90c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="image.png" title="image.png"></p>
<p>使用效果如图:<br><img src="https://upload-images.jianshu.io/upload_images/17817191-15a0fc4ec4265e66.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="image.png" title="image.png"><br><img src="https://upload-images.jianshu.io/upload_images/17817191-7ba1a80601a553fc.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="image.png" title="image.png"></p>
<h3>WEB前端助手</h3>
<p>这个扩展包含多个独立小应用,比如:Json工具、代码美化、代码压缩、二维码、Postman、markdown、网页油猴、便签笔记、信息加密与解密、随机密码生成、Crontab等等!<br><img src="https://upload-images.jianshu.io/upload_images/17817191-d7b8292e30dc79cc.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="image.png" title="image.png"><br>扩展地址 <a href="https://link.segmentfault.com/?enc=AU3kqwwpGO%2BB%2BpsZ944P9w%3D%3D.uxl9iQ2HDxqw5AjPjBNwTHZGuZYyZT79dxTxXF%2BLYpCAZtsPvQyPcYD%2B069uH1ii21JOhEYuDfcZLCSaK1jRjMcBo3i4bVpy%2BgJHORjj%2BknAmcN%2FhwJVbPE%2F%2FPdWBAXuPW2v8tPW1tKyykXB4i%2Fe1WndWSf1%2BxdtJibCKTa%2B1dypFNyUBClsciwhBSWbhzeD" rel="nofollow">https://chrome.google.com/webstore/detail/web%E5%89%8D%E7%AB%AF%E5%8A%A9%E6%89%8Bfehelper/pkgccpejnmalmdinmhkkfafefagiiiad?hl=zh-CN</a></p>
<h3>listen1</h3>
<p>Listen 1可以搜索和播放来自网易云音乐,虾米,QQ音乐,酷狗音乐,酷我音乐网站的歌曲,让你的曲库更全面,不用一个个找了。<a href="https://link.segmentfault.com/?enc=WT98oewP4R6kbxAB0tV10A%3D%3D.dhxBKW31dmxiEQSi%2Bl8b9cyizXWk%2FmhuyZUWCzppjj7vymmDlXZAgEsEwL%2Fz9%2BXC" rel="nofollow">https://listen1.github.io/lis...</a></p>
<p><img src="https://upload-images.jianshu.io/upload_images/17817191-eef4692e567c2a2f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="image.png" title="image.png"><br>之前也写过 <a href="https://link.segmentfault.com/?enc=1NS%2BiAKVUqMzIkv5QX5HVw%3D%3D.u7Fnih%2BFWNxBvz4mJ1ewhw0TkUhdPCgJMbFGNQD5sQ8EHXQjGt7oNv6g7YPCfue%2FCb5rZq%2BHekxDuJC6f5fSLQ%3D%3D" rel="nofollow">那些你可能不知道的网易云音乐奇技淫巧</a></p>
<h3>极简 Json 格式化</h3>
<p>这个用来看json格式的接口最方便了,由<a href="https://link.segmentfault.com/?enc=qflzsv5AA5lZII0WKRNyCA%3D%3D.y0tLutjeHGAPhRO0Y8FY8uYV58Opww3P0c1SQtonqos%3D" rel="nofollow">https://atool.vip/#/</a>提供。<br><img src="https://upload-images.jianshu.io/upload_images/17817191-f325d2e123ce8112.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="image.png" title="image.png"></p>
<p>下载地址 <a href="https://link.segmentfault.com/?enc=%2B5W0ASD0bCSji1Zxr7ejwg%3D%3D.uJhXXhNA11wH917hAWJg%2FY4hbf2Vl8YdVFN8R6DZKcJW1SRuj%2FAjeXDFTq5kfD%2B8E4b7gbA%2BkT6YETzX2vfoKdEu8z6CEx%2FXbbxUPJPQM3CpSrG1y1mAgv%2ByeGBhIAs86JJXronQQ18EGAD9FfWoSEiDSSy1AvSPXO3pd08xEv7fevHknJW63Sp0a%2FoujDSq" rel="nofollow">https://chrome.google.com/webstore/detail/%E6%9E%81%E7%AE%80-json-%E6%A0%BC%E5%BC%8F%E5%8C%96/fhlnfdmpnhhakjljpllkigcegcejpoec?hl=zh-CN</a></p>
<h3>百度网盘助手</h3>
<p>用来下载百度网盘的工具 增加高速下载按钮。</p>
<p><img src="https://upload-images.jianshu.io/upload_images/17817191-23ca4429842e815a.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="image.png" title="image.png"></p>
<p>下载地址 <a href="https://link.segmentfault.com/?enc=yTJB0JCLWF%2FrFNDVuUB%2BOg%3D%3D.wQYSZRQDMMCvd9CAYynEVNOCcaRSCdCCbZJWiFY6XySMzDHSA0vwBBIeQ1BFuNmRCeZ9LNzWgeVxNW%2BzLxIGtw%3D%3D" rel="nofollow">https://github.com/high-speed-downloader/high-speed-downloader</a></p>
<h3>图片助手</h3>
<p>一款Chrome浏览器中用于嗅探、分析网页图片、图片筛选、下载等功能及收藏、检索、分享等在线服务的扩展程序,无论图片是使用flash载入还是动态载入的,扩展都能很好地应对,真正做到所见即所得 <a href="https://link.segmentfault.com/?enc=XIUHr2%2F7%2BYVppIzswPCfLA%3D%3D.qaNH6OAfLZxJk4kN1ix0OD820IncjkMmsRgmEltKpzMaG3UkJTJZntNF9xLv%2BuKE" rel="nofollow">http://www.pullywood.com/ImageAssistant/</a><br><img src="https://upload-images.jianshu.io/upload_images/17817191-4f4c94288819118a.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="image.png" title="image.png"></p>
<p>下载地址<a href="https://link.segmentfault.com/?enc=FgM858dhzD5QK4VZqd9cng%3D%3D.1DXsj8Hqd5pj6LC%2BcVz8%2BoJZ3%2B%2FdT5bPniyM%2FplfpQwgcYp3m%2B1ZORM3HsOHhLidxg92tqDXnFfaWFNL%2BEg3McdlLQbhk9k8E5B3F5nYFvwx6bgHL746n5aUYtfIO9zIteWq55jJHcRjOCDAfIwxvA%3D%3D" rel="nofollow">https://chrome.google.com/webstore/detail/imageassistant-batch-imag/dbjbempljhcmhlfpfacalomonjpalpko</a></p>
<h3>微博图床</h3>
<p>一个上传图片到微博并生成外链的 Chrome 浏览器扩展<a href="https://link.segmentfault.com/?enc=ABa%2FRAbDE%2BgJr1Qc2wJjaQ%3D%3D.A9C7hwLSSqYrvWLWYC2cZbFf4j3r3pwMO17NTjHmbM%2FpC6Ge26SUVn8yFkwGgxRM" rel="nofollow">https://github.com/Semibold/Weibo-Picture-Store</a>,支持同步到微相册 ,需要浏览器登录微博。<br><img src="https://upload-images.jianshu.io/upload_images/17817191-dd79a0d9e1c89cf7.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="image.png" title="image.png"></p>
<p>下载地址 <a href="https://link.segmentfault.com/?enc=z38Rh%2FVHd1N9Ow1pcFZfMA%3D%3D.%2FeCMae3ADl6x3XWvv60basRFD8adC%2FjWzvrxe%2Fs4PE8BumSfUXTlGdKzidDDzu5ZYzzuxXgYJ9F6P%2F8kSFJ3CCcuwxHikgyfDAUh0%2BhZPlw%3D" rel="nofollow">https://chrome.google.com/web...</a></p>
<h3>谷歌访问助手</h3>
<p>这个上谷歌必备 <br><img src="https://upload-images.jianshu.io/upload_images/17817191-e0c8dc4074b512e4.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="image.png" title="image.png"></p>
<p>下载地址<a href="https://link.segmentfault.com/?enc=L1%2BNx648AM5%2F4sTgu4GLDQ%3D%3D.QfnEPz5rBAKNou6EpQisd7ddgDZLVw2S9a9Nii7zwmqRrwByUgPMi2L%2FJUm8Nepk5gy9rFI0qj3Klh%2FzrAYTUFK13OeJm%2BB7ENHL536koWQ%3D" rel="nofollow">https://github.com/haotian-wa...</a> 如果下载不了公众号回复 <code>谷歌</code> 获取</p>
<h3>爱搜资源云盘助手</h3>
<p>之前写过文章 <a href="https://link.segmentfault.com/?enc=MP1BeU2Q1PmanzFQnaEMog%3D%3D.ieKQutos16fVRmiXBPx6ncKY%2BYZDlV6%2BlNg95EYOn2jHvZBvsDx5hbfuJf3VvyU6u%2FT3nb%2FiAmmitOuPT4O%2FKA%3D%3D" rel="nofollow">没有提取码怎么获取百度网盘资源?</a>,不用自己输入提取码。<a href="https://link.segmentfault.com/?enc=t2jFObPrYP96LEknI8zA9w%3D%3D.vKPbsjxfgEeXxDUtLJUPP1NUh937zPVxarYlN5pVNlk%3D" rel="nofollow">https://www.aisouziyuan.com/</a><br><img src="https://upload-images.jianshu.io/upload_images/17817191-9c50d75dd07d538a.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="image.png" title="image.png"></p>
<p>下载地址 <a href="https://link.segmentfault.com/?enc=%2FNuO6iJIogx2zN5KScB7XQ%3D%3D.w%2FbskbLXfFLf7PHwBfVe%2Fzwe2KRffCiI4SgkZ4YdTJ7wlv2iKt8%2FlQqq9jT83KuuM6GpwQPhC1aA4QE41WUHXSZ%2B8vGFvLL2TeCTcswhEdUE%2B6iGyMEk4ikGvkBNzB4zSNrs5d7fEgyS7eLlcC1k%2FvLAbbXZYsYc2KSq5ryYFW8egNPC%2Bb3%2FA%2BedZdWqZsbIw3F8RLwFivhLPH6LTZ2pKUci5GmUPeihBQ4C79CGMO2pRqvvdLCfoLXbjwNlJrzG" rel="nofollow">https://chrome.google.com/web...</a></p>
<h3>一键视频下载器</h3>
<p>比如微博上的视频,点击按钮就能显示当前可以下载的视频,直接点击下载到本地。<br><img src="https://upload-images.jianshu.io/upload_images/17817191-de4d190cdfd3d06f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="image.png" title="image.png"><br>下载地址 <a href="https://link.segmentfault.com/?enc=g37g4n4Naqn7ZFDM0vWi%2BA%3D%3D.0XjmRk%2F25VKyESBrf8IjkGgW0HYNRyVa%2BbIm34wAz8yEroBq%2BccWBML1Dl3%2Bc2eGHRoe%2BX%2B8AmBcPWYzzUvmD35ZdJ61saHsq0%2FU5ZlW117iQFsFTw1yzBnIfjcZMpZ4ZtxfOi7eO3cQX6wuOHCL6w%3D%3D" rel="nofollow">https://chrome.google.com/webstore/detail/one-click-video-downloade/bhepgcoaibmmehlmckhlmbdgcemhidcg</a></p>
<h3>翻译</h3>
<p>co-trans-ext 是一个集搜狗翻译、百度翻译、谷歌翻译、有道翻译、金山词霸于一体的翻译扩展。各平台可随时切换,取长补短,更适合于阅读各领域的文档。不止于翻译,解析详细,更利于对各门语言的深入学习与理解。支持划词翻译和网页翻译。<br>下载后将crx后缀改为zip,然后拖到扩展中,除了翻译还提供发音,非常好用。</p>
<p><img src="/img/bVbygdJ" alt="clipboard.png" title="clipboard.png"></p>
<p>下载地址:<a href="https://link.segmentfault.com/?enc=%2BddBc8tYK%2FH%2BIFQTeBupaQ%3D%3D.AiDulFfZUgG2bdlDqaRKhbMxBXRXG51ayvWQIQ2a10Rzwi7fiGFuwFZwjDleNgjs" rel="nofollow">https://github.com/Coande/co-trans-ext</a></p>
<h3>截图</h3>
<p>它满足截图所有的需求,截取可见网页,选择区域,整个网页,录屏,捕获整个页面或任何部分,矩形,圆形,箭头,线条和文字,模糊敏感信息,一键上传分享注释。<br><img src="https://upload-images.jianshu.io/upload_images/17817191-7a49328c5baf176b.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="image.png" title="image.png"><br><img src="https://upload-images.jianshu.io/upload_images/17817191-4dcae7ed5ab8b479.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="image.png" title="image.png"></p>
<p>下载地址<a href="https://link.segmentfault.com/?enc=DNMmiGKb4eEDTlDBas722A%3D%3D.skSRLMnj6KdQ2xbLfP8WTMYw6FbyGCg44cXXMjHwBoXCE9A8JZXSBA6JXzsr%2Fcix73rlVWgLETBxoAOeKTg508Q%2FrcLAdm9TgjnFh24UULDCxWbg6eKfNGG95MpkKE5hMjIxb6GjwkymfcHFWP4Oqw%3D%3D" rel="nofollow">https://chrome.google.com/webstore/detail/awesome-screenshot-screen/nlipoenfbbikpbjkfpfillcgkoblgpmj</a></p>
<h3>聊天</h3>
<p>和浏览相同网页的人实时聊天,发弹幕!<a href="https://link.segmentfault.com/?enc=faboiEecR9YMwz31XJBl3Q%3D%3D.%2Foouht5pzEqaQYY7E%2B049ODta4%2FJpeszQttAELl7kyQ%3D" rel="nofollow">http://yiyechat.com/</a><br>该扩展可以在任意网页增加一个简洁的聊天盒,让您可以和浏览当前网站的其他用户聊天!</p>
<p>这是谷歌页面的聊天</p>
<p><img src="/img/bVbygdK" alt="clipboard.png" title="clipboard.png"></p>
<p>下载地址 <a href="https://link.segmentfault.com/?enc=hKH4Yi%2FRuLhpfURGD3DsHg%3D%3D.05u%2BTX4TNVCV0wmFYaJyp1aSN8euclFsSvFJ%2F3CQzvW7g3IiQwkMLxKvdZLqJLAgd2F0Hy4i%2Fk3W9qKDvBgmR%2Fwdjo1XyWDuTU3EFfYpErVIXpt5NZQ1tfaIfuRfONWh" rel="nofollow">https://chrome.google.com/web...</a></p>
<h3>复制图片中文字</h3>
<p>这个Chrome扩展厉害了 ,能直接复制图片中文字,功能远超普通OCR软件 <a href="https://link.segmentfault.com/?enc=qQ85jlcSFP4W7PW1Occruw%3D%3D.Oi8bNq686Yx0ueqTdjLyoOXbKxsBw%2Bbrpl4RA5PLq5g%3D" rel="nofollow">https://projectnaptha.com/</a></p>
<p><img src="/img/bVbygdL" alt="clipboard.png" title="clipboard.png"></p>
<p>你平常用了哪些不错的扩展,也欢迎评论给我推荐下。</p>
<p>推荐阅读:</p>
<p><a href="https://link.segmentfault.com/?enc=L6dt2lYH7exRaz%2BuKb5EPA%3D%3D.AWTvlAP12OJ9LdfNfJ8X9TVwOVrdL3omcYGNqhNRh8JCrMgRgwzY32Zxvl%2FTsG92fk31AxEDZMZ8xY3jglS%2BBg%3D%3D" rel="nofollow">那些你可能不知道的浏览器奇技淫巧</a></p>
<p><a href="https://link.segmentfault.com/?enc=1t9%2FF0aou79NA8ezErjGJg%3D%3D.q1c%2F%2FND50xbCl9DA5DbdsWRD8fJN4odmFAW3ugudNE6dxV7cwaOUhmNBzHQQ7gcG9ubIv2Ze6dHAYyhwpyjq3w%3D%3D" rel="nofollow">如何发一条空白的朋友圈</a></p>
<p><a href="https://link.segmentfault.com/?enc=cl5Sd%2BrNtF2O7aEGgTd3ig%3D%3D.H2zaL%2BhI5%2FhNeHp5sKZvzsSBLTweMSq2NDWbZGgZfxB6a7jW9pEaxB08ySNMN0yxjeHtrz97Oec3PUJEnJl8Lg%3D%3D" rel="nofollow">如何在电脑上登陆多个微信</a></p>
<p><a href="https://link.segmentfault.com/?enc=niIt8uuBJKkASGhYAN76Zg%3D%3D.z4L1ZOMQ56PxDxvUt%2BQv1DZF6DLcdNwlnr44oyS8Bx4XGes1OAP1yK2ZkBN8fE29u4t61vnORfwqElbcygO4rA%3D%3D" rel="nofollow">如何提取公积金 9 天到账</a></p>
<p><a href="https://link.segmentfault.com/?enc=%2BdGwUStZgeWNXEyzrPRl%2FQ%3D%3D.BLcgOq0%2F5XygxXDOd239zK54cCd2gHrIsm1y7RORl8K9AEGCUUZl5ri%2B0sVdmphizWl8ASO6hOGu6AmubhtxCw%3D%3D" rel="nofollow">免费在线听周杰伦歌曲</a></p>
<p><a href="https://link.segmentfault.com/?enc=R0l5nsW44Wtewx%2FnbWxubw%3D%3D.TzVSs%2Bx56oODX3P8Qx0q84MLjaHL87MdSd2z9yD%2FLBCU1JIdDXv6nZwHwJiENFGTpEB1%2BSiQgSl%2FQ2nw8fK3%2Bg%3D%3D" rel="nofollow">那些你可能不知道的微信奇技淫巧</a></p>
<p><a href="https://link.segmentfault.com/?enc=fdzGI4cwQ1NuEZXQsMtnyg%3D%3D.dMzete9q%2F%2FgpCyUAc2I1Im%2FzWBLDYFludNvYYRYRESsoU3UUY9DNHrulakmLoAAzjyfswodZ3c1V28JcOf%2BFpA%3D%3D" rel="nofollow">如何在豆瓣租房小组快速找到满意的房子</a></p>
<p><a href="https://link.segmentfault.com/?enc=3jjl%2Faa66NTiuHK34Taqdw%3D%3D.%2FcXX3%2FpzpHR52j0wK7VnSFYeSjbtxLCUcEysCOHXtaQCJO9v0kVwrZiqtVpZXo95LGhexKFwx5nbL1L%2FbLGrWQ%3D%3D" rel="nofollow">10%+10% 不等于 0.2?</a></p>
<p><a href="https://link.segmentfault.com/?enc=Bb53N9voiVwk9AHe%2BqTryA%3D%3D.3f2jjyqpkiCObapKeIErUXeCnZ0daVV4Lv%2BrJHWFmS40qC2AXoT8Eclb%2Bl4KYiJRqZsk1TqGTPbxKopghySseQ%3D%3D" rel="nofollow">Chrome 浏览器扩展神器油猴</a></p>
<p><img src="/img/remote/1460000019754928" alt="免费星球" title="免费星球"></p>
<h3>公众号:苏生不惑</h3>
<p><img src="/img/remote/1460000019152534" alt="扫描二维码关注" title="扫描二维码关注"></p>
各种数据库命令行工具 mycli litecli mssql-cli pgcli
https://segmentfault.com/a/1190000019824718
2019-07-21T07:56:59+08:00
2019-07-21T07:56:59+08:00
苏生不惑
https://segmentfault.com/u/sushengbuhuo
5
<p>如果你平常在命令行操作数据库,强烈推荐你使用下面的几个命令行工具了。</p>
<h3>mycli</h3>
<p>mycli 是基于MySQL的命令行工具,直接使用<code> pip install mycli</code> 安装,<br> 具体介绍见 <a href="https://link.segmentfault.com/?enc=0L8QD7lhTyxon5WvLQVgiA%3D%3D.0LBljzTgfkSKrKnH3i2GvQKPhonNf5C7499zRKfZRCg%3D" rel="nofollow">https://github.com/dbcli/mycli</a></p>
<pre><code class="js">$ mycli --help
Usage: mycli [OPTIONS] [DATABASE]
A MySQL terminal client with auto-completion and syntax highlighting.
Examples:
- mycli my_database
- mycli -u my_user -h my_host.com my_database
- mycli mysql://my_user@my_host.com:3306/my_database
Options:
-h, --host TEXT Host address of the database.
-P, --port INTEGER Port number to use for connection. Honors
$MYSQL_TCP_PORT.
-u, --user TEXT User name to connect to the database.
-S, --socket TEXT The socket file to use for connection.
-p, --password TEXT Password to connect to the database.
--pass TEXT Password to connect to the database.
--ssh-user TEXT User name to connect to ssh server.
--ssh-host TEXT Host name to connect to ssh server.
--ssh-port INTEGER Port to connect to ssh server.
--ssh-password TEXT Password to connect to ssh server.
--ssh-key-filename TEXT Private key filename (identify file) for the
ssh connection.
--ssl-ca PATH CA file in PEM format.
--ssl-capath TEXT CA directory.
--ssl-cert PATH X509 cert in PEM format.
--ssl-key PATH X509 key in PEM format.
--ssl-cipher TEXT SSL cipher to use.
--ssl-verify-server-cert Verify server's "Common Name" in its cert
against hostname used when connecting. This
option is disabled by default.
-V, --version Output mycli's version.
-v, --verbose Verbose output.
-D, --database TEXT Database to use.
-d, --dsn TEXT Use DSN configured into the [alias_dsn]
section of myclirc file.
--list-dsn list of DSN configured into the [alias_dsn]
section of myclirc file.
-R, --prompt TEXT Prompt format (Default: "\t \u@\h:\d> ").
-l, --logfile FILENAME Log every query and its results to a file.
--defaults-group-suffix TEXT Read MySQL config groups with the specified
suffix.
--defaults-file PATH Only read MySQL options from the given file.
--myclirc PATH Location of myclirc file.
--auto-vertical-output Automatically switch to vertical output mode
if the result is wider than the terminal
width.
-t, --table Display batch output in table format.
--csv Display batch output in CSV format.
--warn / --no-warn Warn before running a destructive query.
--local-infile BOOLEAN Enable/disable LOAD DATA LOCAL INFILE.
--login-path TEXT Read this path from the login file.
-e, --execute TEXT Execute command and quit.
--help Show this message and exit.
λ mycli -u root
Password:
mysql 5.5.53
mycli 1.19.0
Chat: https://gitter.im/dbcli/mycli
Mail: https://groups.google.com/forum/#!forum/mycli-users
Home: http://mycli.net
Thanks to the contributor - Jialong Liu
mysql root@localhost:(none)> show data
databases
create database</code></pre>
<p><img src="/img/bVbvltC?w=483&h=199" alt="clipboard.png" title="clipboard.png"></p>
<p>语法高亮 和 自动补全</p>
<p><img src="/img/bVbvltD?w=732&h=113" alt="clipboard.png" title="clipboard.png"></p>
<p>ps:进入MySQL命令行后如果想执行Linux命令怎么办,先退出执行然后再登录MySQL?麻烦,其实可以直接用system。</p>
<pre><code class="js">mysql> system pwd
/root
mysql> system ll
sh: ll: command not found
mysql> system ls -al
total 40160
dr-xr-x---. 39 root root 4096 Jul 10 14:47 .
dr-xr-xr-x. 29 root root 4096 May 5 18:55 ..
</code></pre>
<h3>litecli</h3>
<p>litecli 是基于 sqlite 的命令行工具,直接用 <code>pip install -U litecli </code> 安装,具体介绍见<br><a href="https://link.segmentfault.com/?enc=h9H3WCElpEUsYByclXT1qw%3D%3D.FBlxHNO%2FCZAc9wgfdbpyD8GpvCcGi7XQHX21N7T%2B6KCUtqfU6HR2QbAcz5Uc6gU0" rel="nofollow">https://github.com/dbcli/litecli</a></p>
<pre><code class="js">$ litecli --help
Usage: litecli [OPTIONS] [DATABASE]
A SQLite terminal client with auto-completion and syntax highlighting.
Examples:
- litecli lite_database
Options:
-V, --version Output litecli's version.
-D, --database TEXT Database to use.
-R, --prompt TEXT Prompt format (Default: "\d> ").
-l, --logfile FILENAME Log every query and its results to a file.
--liteclirc PATH Location of liteclirc file.
--auto-vertical-output Automatically switch to vertical output mode if the
result is wider than the terminal width.
-t, --table Display batch output in table format.
--csv Display batch output in CSV format.
--warn / --no-warn Warn before running a destructive query.
-e, --execute TEXT Execute command and quit.
--help Show this message and exit.
λ litecli
Version: 1.0.0
Mail: https://groups.google.com/forum/#!forum/litecli-users
Github: https://github.com/dbcli/litecli
(none)> .tables
Not connected to database.
(none)> .databases
Not connected to database.
(none)> use test
You are now connected to database "test"
Time: 0.001s
test> .tables
Time: 0.000s
test> CREATE TABLE COMPANY(
ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY REAL
);
Query OK, 0 rows affected
Time: 0.077s
test> .tables
+---------+
| name |
+---------+
| COMPANY |
+---------+
Time: 0.040s</code></pre>
<p><img src="/img/bVbvltE?w=628&h=489" alt="clipboard.png" title="clipboard.png"></p>
<p>使用语法见 <a href="https://link.segmentfault.com/?enc=dl4f6rAL8E0bvRciWR6N5Q%3D%3D.JcK8SXTLyRCeg4pLCHLKy3XGk5iFi7%2FJMxUgxqzCKA5mDikcSsxfL%2B6x%2F016ZjYyBKJrPdE7GhMRhY3Tb2yBIA%3D%3D" rel="nofollow">https://www.runoob.com/sqlite/sqlite-insert.html</a></p>
<pre><code class="js">test> INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (1, 'Paul', 32, 'California', 20000.00 );
Query OK, 1 row affected
Time: 0.083s
test> select *from `COMPANY`
+----+------+-----+------------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+------+-----+------------+---------+
| 1 | Paul | 32 | California | 20000.0 |
+----+------+-----+------------+---------+
1 row in set
Time: 0.023s
test> SELECT CURRENT_TIMESTAMP;
+---------------------+
| CURRENT_TIMESTAMP |
+---------------------+
| 2019-07-10 06:49:09 |
+---------------------+
1 row in set
Time: 0.017s
test> UPDATE COMPANY SET ADDRESS = 'Texas' WHERE ID = 1;
Query OK, 1 row affected
Time: 0.097s
test> select *from `COMPANY`
+----+------+-----+---------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+------+-----+---------+---------+
| 1 | Paul | 32 | Texas | 20000.0 |
+----+------+-----+---------+---------+
1 row in set
Time: 0.019s</code></pre>
<p><img src="/img/bVbvltF?w=590&h=512" alt="clipboard.png" title="clipboard.png"></p>
<h3>mssql-cli</h3>
<p>mssql-cli是基于mssql 的命令行工具,直接用<code> pip install mssql-cli</code>安装,具体介绍见 <a href="https://link.segmentfault.com/?enc=KC%2FcEMYvwFRm2FefGfkxmg%3D%3D.Y6rUUNput3tRzhTt6ZJ1m3InN7%2F70hIRAvhBaZUy367k2xCeHlm7ohIUuBcNJOv8" rel="nofollow">https://github.com/dbcli/mssq...</a> <a href="https://link.segmentfault.com/?enc=6klCcTQ41MbjsPe1%2BaYw5A%3D%3D.ub8i9RUcX802orTLCs0bySXRaSI3qIqVDL6I3OVLIFMIsVNaPj%2BqcAAn38hcy2av" rel="nofollow">https://www.ctolib.com/dbcli-...</a></p>
<pre><code class="js">$ mssql-cli --help
usage: mssql-cli [-h] [-U] [-P] [-d] [-S] [-E] [-v] [--mssqlclirc]
[--row-limit] [--less-chatty] [--auto-vertical-output] [-N]
[-C] [-l] [-K] [-M] [-a] [-A]
[--enable-sqltoolsservice-logging] [--prompt]
Microsoft SQL Server CLI. Version 0.15.0
optional arguments:
-h, --help show this help message and exit
-U , --username Username to connect to the database
-P , --password If not supplied, defaults to value in environment
variable MSSQL_CLI_PASSWORD.
-d , --database database name to connect to.
-S , --server SQL Server instance name or address.
-E, --integrated Use integrated authentication on windows.
-v, --version Version of mssql-cli.
--mssqlclirc Location of mssqlclirc config file.
--row-limit Set threshold for row limit prompt. Use 0 to disable
prompt.
--less-chatty Skip intro on startup and goodbye on exit.
--auto-vertical-output
Automatically switch to vertical output mode if the
result is wider than the terminal width.
-N, --encrypt SQL Server uses SSL encryption for all data if the
server has a certificate installed.
-C, --trust-server-certificate
The channel will be encrypted while bypassing walking
the certificate chain to validate trust.
-l , --connect-timeout
Time in seconds to wait for a connection to the server
before terminating request.
-K , --application-intent
Declares the application workload type when connecting
to a database in a SQL Server Availability Group.
-M, --multi-subnet-failover
If application is connecting to AlwaysOn AG on
different subnets, setting this provides faster
detection and connection to currently active server.
-a , --packet-size Size in bytes of the network packets used to
communicate with SQL Server.
-A, --dac-connection Connect to SQL Server using the dedicated
administrator connection.
--enable-sqltoolsservice-logging
Enables diagnostic logging for the SqlToolsService.
--prompt Prompt format (Default: \d>
</code></pre>
<h3>pgcli</h3>
<p>pgcli 是一个基于 PostgreSQL 的命令行工具,支持自动补全和语法高亮,直接使用<code>pip install -U pgcli </code> 安装,具体介绍见 <a href="https://link.segmentfault.com/?enc=bap2ilOxwl%2BtN3dWhHF87w%3D%3D.ZqZgIC5U8vvjV6igP35fVoxZyOQ7t7ZTmytiCodUSkQ%3D" rel="nofollow">https://github.com/dbcli/pgcli</a></p>
<pre><code class="js">$ pgcli --help
Usage: pgcli [OPTIONS] [DATABASE] [USERNAME]Options:
-h, --host TEXT Host address of the postgres database.
-p, --port INTEGER Port number at which the postgres instance is listening.
-U, --user TEXT User name to connect to the postgres database.
-W, --password Force password prompt.
-w, --no-password Never prompt for password.
-v, --version Version of pgcli.
-d, --dbname TEXT database name to connect to.
--pgclirc TEXT Location of pgclirc file.
--help Show this message and exit.</code></pre>
<p>推荐阅读:</p>
<p><a href="https://link.segmentfault.com/?enc=ONsty6geAeaSi1m%2FP81VXA%3D%3D.VSMFrNXTq4WSlhh72HWGCTe8q1xumzXyD7MryHr3SQ7KjLobvDPFDGB5t3%2B4hpJDV0ZjywVn8DjiZMMCNsxNOg%3D%3D" rel="nofollow">5 分钟使用 hugo 搭建一个自己的博客</a></p>
<p><a href="https://link.segmentfault.com/?enc=QnBoDtbrt6Nw2IODLBE8Tw%3D%3D.IItFHnvy1CSzikz5CX5OradvQ17wu7xY%2FoQ%2BdAcV9rGgvM8Ug90%2BgvHDY2l57WX%2BTxFpsJpAVigKX3x%2Fffo%2F1g%3D%3D" rel="nofollow">Python 文档生成器 mkdocs</a></p>
<p><a href="https://link.segmentfault.com/?enc=69LDpDq%2F4Mnun96f9i2ZJA%3D%3D.zNpacgUlidQIoyT4vBUjrrunhQbv3LaTWNIla%2FfMLuhM4hpsH%2FQsfXyaqeu9X4XAYzKp7Ar4zMQ6rGS1HaRWag%3D%3D" rel="nofollow">比 man 更强悍的命令行工具 cheat</a></p>
<p><a href="https://link.segmentfault.com/?enc=iz8vJBtMTJoZOZCGg%2BVmJQ%3D%3D.XYPrsQLfcTmk6mXmYFQpdeEOtsKEQrzqHW8ol8PQcPiLSVkNiUrwt%2BcVM%2Buiim5IP5lKFzAJ4nDp%2B9aTxxO8Ig%3D%3D" rel="nofollow">上班摸鱼好去处</a></p>
<p><a href="https://link.segmentfault.com/?enc=M9MWwdb97PXeWYqLSG23%2FA%3D%3D.YANYBR7ET5T8HRDsMgYSYPhQ2si8%2Fraz5XPfb3XRG6qXevb%2FJ0Tkp%2BlVViaGm6qwxtWzowKFdxBcUJYiVCyngQ%3D%3D" rel="nofollow">命令行录制工具 asciinema</a></p>
<h3>公众号:苏生不惑</h3>
<p><img src="/img/remote/1460000019152534" alt="扫描二维码关注" title="扫描二维码关注"></p>
Chrome 浏览器扩展神器油猴
https://segmentfault.com/a/1190000019754907
2019-07-14T10:28:49+08:00
2019-07-14T10:28:49+08:00
苏生不惑
https://segmentfault.com/u/sushengbuhuo
8
<p>我平常工作最常用的浏览器就是 Chrome 了,Google 出品,值得信赖,用 Chrome 就不得不提浏览器扩展了,有了各种 Chrome 扩展,可以让你浏览器网页更方便,工作更高效。</p>
<p>Chrome 扩展可以在 Google 应用商店下载 <a href="https://link.segmentfault.com/?enc=%2B%2FQ55jH7VKXuJ7TtHPCokg%3D%3D.Qm%2BlDP4YEKTX9CQFzzYSxisnaoOvav%2BdO7vEORmhidOWSY9zNgsTm84AT70YPLNy86fIFkxX4N1D2EZX7lPUTg%3D%3D" rel="nofollow">https://chrome.google.com/webstore/category/extensions?hl=zh-CN</a><br> 这里可以搜索安装你喜欢的各种扩展。<br><img src="/img/remote/1460000019754910" alt="image.png" title="image.png"></p>
<p>比如我装了很多扩展。<br><img src="/img/remote/1460000019754911" alt="image.png" title="image.png"></p>
<p>扩展这么多,其中的油猴<code> Tampermonkey</code> 是必须推荐的一个,它是扩展中的王者,最强大的浏览器扩展。</p>
<h3>安装油猴扩展</h3>
<p>油猴是个Chrome扩展,网站 <a href="https://link.segmentfault.com/?enc=sZCjvEgQSwHtnyQMKjX3zQ%3D%3D.d7GWZ5CEyyUp1MSiVy0vjFwnLjRNRI3%2B6MSVKq6vTL0%3D" rel="nofollow">https://www.tampermonkey.net/</a> 可以直接在官网下载 <a href="https://link.segmentfault.com/?enc=GAj6ZLYFFIjyUfmkcbqoGQ%3D%3D.DNKvnJQPnNDf6zqsaljfmjC6qhCf0R8z%2BosZ0Z7tOqhMZqnr%2BQZ1PxMH3YGlwigraXCXSIBmtv0cr%2BvHx1s2osBvo1W8512WPT7ASrhgWZqBKzVR6LlOrMc7Z2V1nhWiBG2Mw8VgNNN3uaXzXnmv4Q%3D%3D" rel="nofollow">https://chrome.google.com/web...</a> 直接安装即可。</p>
<p>如果上不了Google,可以在国内第三方Chrome 插件网站<br><a href="https://link.segmentfault.com/?enc=PbUPWUuTQnm35aZOXoQRjg%3D%3D.7CZwQCTZnm%2BSn3156O1lR%2FXBXkZq0uhWDjjUfrQt5rc%3D" rel="nofollow">https://www.crx4chrome.com/</a> <br><a href="https://link.segmentfault.com/?enc=0D9xKttupSbBF55MBOxQRQ%3D%3D.4UxHKGAL9ypwmis1s7JXX5ZIm9L67YMBrMpbW2ByDJM%3D" rel="nofollow">http://chromecj.com/</a> <br><a href="https://link.segmentfault.com/?enc=ELbfJD5VQlA9Aquc5P4hEg%3D%3D.UitSvsR0tdDel4V4dLQoEkV97yZHud5hEl6iY2N2HLo%3D" rel="nofollow">http://www.cnplugins.com/</a> <br><a href="https://link.segmentfault.com/?enc=X%2FrwKZBLEBRULDhEiCch%2Bw%3D%3D.GB2ikIZGFqNdNCzMk4FSh07IbUuZ7nGLLapGc42lQQk%3D" rel="nofollow">https://www.chromefor.com/</a> <br>等搜索下载。下载的是个 crx 文件,然后打开 Chrome 扩展<a>chrome://extensions/</a>,打开开发者模式,将下载的crx文件拖进去,如果出错提示程序包无效。<br><img src="/img/remote/1460000019754912" alt="image.png" title="image.png"><br>将 crx 后缀改为 zip 再拖进去就能安装成功了,浏览器右上角可以看到图标。</p>
<p><img src="/img/remote/1460000019754913" alt="image.png" title="image.png"></p>
<h3>脚本网站</h3>
<p>有了油猴扩展,还需要配上脚本。<br>安装完扩展后点击图标,选择 获取新脚本<br>会进入网站<a href="https://link.segmentfault.com/?enc=p2c14nTLClBXY0JktigRyw%3D%3D.sMzyRAtIZ%2FJkPBWQ9ssBKfYavtvgOS1%2BL3h7Ekp9v7Vm3hUk1xRPv%2BrPg8TNAPX0" rel="nofollow">https://www.tampermonkey.net/scripts.php</a> <br>这里可以获取脚本来源,有3个来源网站<br><a href="https://link.segmentfault.com/?enc=dg0AH7uF57AGg8JIBVCMpg%3D%3D.GWJLy7HPj3uiOqd5ZgXSuoMtqiOPE%2ByBkgfKA4Sev8c%3D" rel="nofollow">http://userscripts-mirror.org/</a><br><a href="https://link.segmentfault.com/?enc=D2Jj4a0btl3ldrHOJ4nqSw%3D%3D.r3wpABPjDzZHLmNZplxx1dgi%2FVCDXvsmx5t%2Be4O6b6I%3D" rel="nofollow">https://openuserjs.org/</a> <br><a href="https://link.segmentfault.com/?enc=ntzLYPT1srvI9mc8beuHOQ%3D%3D.ir9ZHyYJd9fByk0PHnlZw9%2FoB%2BJvnz1oBHFzkA2gJtE%3D" rel="nofollow">https://greasyfork.org/</a> <br>这里推荐 greasyfork ,因为它支持中文。</p>
<p>打开网站首页<a href="https://link.segmentfault.com/?enc=gigzeQxtbNfkJdp4QtjxPQ%3D%3D.p7G5MeSK6MdXvrKqui9rHcpMbsx5tRbWB6kyWYV6vE8%3D" rel="nofollow">https://greasyfork.org/zh-CN</a> 可以看到很多脚本。<br><img src="/img/remote/1460000019754914" alt="image.png" title="image.png"></p>
<p>安装脚本也很简单,找到需要的脚本,进入页面,点击安装,然后管理面板即可看到已安装的脚本。</p>
<p>下面推荐些实用的脚本,开始打开新世界的大门。</p>
<h3>搜索去广告</h3>
<p>功能介绍:<br>去掉百度、搜狗、谷歌搜索结果的重定向,回归为网站的原始网址---附带有去除百度的广告 包括百度顶部和底部的垃圾广告,脚本地址<a href="https://link.segmentfault.com/?enc=HxrlLrhQZXhkbGQ0hLmXgA%3D%3D.MHwY2OfesHFlALtzUcka0mh%2B3K64I8MSm3divBdmUAOr%2FHwAcudJhrhKUCyOGQ%2FX" rel="nofollow">https://greasyfork.org/zh-CN/scripts/14178</a></p>
<p>安装脚本前搜索 浏览器 前面3个是广告<br><img src="/img/remote/1460000019754915" alt="image.png" title="image.png"></p>
<p>安装脚本后的效果,广告没有了,你还可以自定义设置。<br><img src="/img/remote/1460000019754916" alt="image.png" title="image.png"></p>
<h3>知乎网页助手</h3>
<p>功能介绍:<br>1、知乎站外链接直接跳转至目标网址;<br>2、自动展开问题全部信息,同时展示所有回答;<br>3、去除知乎网页中的广告;<br>4、知乎网页中短视频下载;<br>5、解除知乎复制限制-划词复制(鼠标左键划词自动添加到剪切板)</p>
<p>脚本地址 <a href="https://link.segmentfault.com/?enc=KsBg70SMl1l%2BC4S2T9e8Xg%3D%3D.CywcyZkLI4JhSHTdpKcKPvz9iXug6JpIgvAQSvo%2B1GWJwPf9IxM8gIrgKNawr3NZ" rel="nofollow">https://greasyfork.org/zh-CN/scripts/384172</a></p>
<p>比如这个周杰伦的视频回答 <a href="https://link.segmentfault.com/?enc=C05AVhADwZVLTmuNh5KMLA%3D%3D.G%2B%2FStFBRnkoZrxbSz9ujVryFvh1RS%2F9oitNFfG1ndNzc0D5uaCwtvb8E8dh701ZhG0m3b3r4%2FTVDAH8ZsFTZcA%3D%3D" rel="nofollow">https://www.zhihu.com/questio...</a><br>安装脚本前<br><img src="/img/remote/1460000019754917" alt="image.png" title="image.png"><br>安装后视频可以直接下载了。<br><img src="/img/remote/1460000019754918" alt="image.png" title="image.png"></p>
<h3>微博浮图</h3>
<p>功能介绍:<br>微博浮图控件,鼠标移过小图弹出浮动大图的脚本。<br>脚本地址<a href="https://link.segmentfault.com/?enc=OBpdSziELBUD%2FC6jqaGmtQ%3D%3D.AYb0neA47jTCp7VNyFxBiw%2Bt8m1l3BHHwqglxLg6tEy9TD%2BoYhfZPdbMJXRl%2FN87" rel="nofollow">https://greasyfork.org/zh-CN/scripts/4233</a><br><img src="/img/remote/1460000019754919" alt="image.png" title="image.png"><br>安装脚本前需要点击小图才能看到大图<br><img src="/img/remote/1460000019754920" alt="image.png" title="image.png"><br>安装后效果,不用点击鼠标移上去即可看到大图,其实不限制微博,其他网站的图片一样可以。<br><img src="/img/remote/1460000019754921" alt="image.png" title="image.png"></p>
<h3>百度网盘直链下载助手</h3>
<p>功能介绍:<br>免客户端一键获取百度网盘文件真实下载地址,支持使用IDM,迅雷等下载工具下载。<br>安装后会在对应界面出现【下载助手】按钮, 配合多线程下载工具达到提速的效果。脚本地址 <a href="https://link.segmentfault.com/?enc=kkfFFoqdu4g7newoN5taRA%3D%3D.63UQNdEW7l4GoQC0Trl0csd009fOIRYdhtadzWi3Y8NmAVLBVDticx9qN%2FuroqrB" rel="nofollow">https://greasyfork.org/zh-CN/scripts/39504</a></p>
<p>安装后不用安装网盘客户端就可以直接下载文件。<br><img src="/img/remote/1460000019754922" alt="image.png" title="image.png"></p>
<h3>全网VIP视频免费破解</h3>
<p>功能介绍:<br>懒人专用,全网VIP视频免费破解去广告、全网音乐直接下载、百度网盘直接下载、知乎视频下载等多合一版。<br>脚本地址<a href="https://link.segmentfault.com/?enc=EK9iY00HR%2F1eyqGopfycqw%3D%3D.Tq4dMPROPGrJnuHm4KbGnuaI6WEYDnNTz4Q4p3S%2FeH7LfOZAQFvAD9z6ikBoJfKK" rel="nofollow">https://greasyfork.org/zh-CN/scripts/370634</a></p>
<p>打开优酷看《 长安十二时辰》,16集开始需要VIP<a href="https://link.segmentfault.com/?enc=u60n4Vqd49%2BGkYlV7A78jQ%3D%3D.qwrVgFzFDhptRyZ0UDN33V2ZdOj4u8%2FWRqMx%2BKxEn9KSvYvwKNF1MF6uJszxRd%2F2UBACVsWJ8LutUVi1ygAkLQ%3D%3D" rel="nofollow">https://v.youku.com/v_show/id_XNDI2NTAzNzQzNg==.html</a></p>
<p><img src="/img/remote/1460000019754923" alt="image.png" title="image.png"><br>安装脚本后,点击左侧的VIP可以跳转到VIP解析网站观看。<br><img src="/img/remote/1460000019754924" alt="image.png" title="image.png"><br><img src="/img/remote/1460000019754925" alt="image.png" title="image.png"><br> 如果看不了,换接口解析。<br><img src="/img/remote/1460000019754926" alt="image.png" title="image.png"></p>
<h3>豆瓣资源下载大师</h3>
<p>功能介绍:<br>聚合数百家资源网站,通过右侧边栏1秒告诉你哪些网站能下载豆瓣页面上的电影|电视剧|纪录片|综艺|动画|音乐|图书等,有资源的网站显示绿色,没资源的网站显示黄色,就这么直观。</p>
<p>脚本地址 <a href="https://link.segmentfault.com/?enc=Epk8FhVhaIIkAS9imnDPIA%3D%3D.Q%2F8SoqfxL8KL30zfM2PuU6jxWtS8gX3dmuBWr2UVNckj3DkdLToQ%2FC5KJ8c5U7Pz" rel="nofollow">https://greasyfork.org/zh-CN/scripts/329484</a></p>
<p>看看最近上映的电影《蜘蛛侠:英雄远征》 <a href="https://link.segmentfault.com/?enc=rcaoWPYib%2FwYPEe2zcNKJw%3D%3D.VL%2BrUe7Ez%2B7qb3P7TC7Ll4P5HnFm0XE00XYolGtHHYsCbcQe7A8zMZSRNU1Ffv%2BaO9WWyWMMMIWQ3%2Bq9qPSqtQ%3D%3D" rel="nofollow">https://movie.douban.com/subject/26931786/?from=showing</a><br>右侧可以看到 中文影视字幕和影视精准匹配,可以到对应网站查看。<br><img src="/img/remote/1460000019754927" alt="image.png" title="image.png"></p>
<p>更多其他脚本自己搜索吧,有什么问题可以评论交流。</p>
<p>推荐阅读:</p>
<p><a href="https://link.segmentfault.com/?enc=sQ58Mw99qrAIvOJ8McrOEQ%3D%3D.1q1n5BKDi56O9Xrfiyjkx%2BTITg6SoYLRr7%2B4FVVLKCBLEDPRZjHo0feYELXzJcf2KXZYfrS5cphGraaXyWzx6A%3D%3D" rel="nofollow">那些你可能不知道的浏览器奇技淫巧</a></p>
<p><a href="https://link.segmentfault.com/?enc=VJ%2FQ3944EYE3GaOayvxj5w%3D%3D.UCOTjAuiUxADkiYmRv%2B%2BGc7wR4n9VSXcZqJLuhACR686T93OrEbSkjw6%2BN17n9VodzF7CPxymAJC6WVpORMCAA%3D%3D" rel="nofollow">那些你可能不知道的微信奇技淫巧</a></p>
<p><a href="https://link.segmentfault.com/?enc=NR%2BDmy4FLalrlPiSuEiqJg%3D%3D.LJlsBH0V4PD1sBeZXxST2CkWGe%2FkM0fO%2FQgetWDkJE%2FuJcAnJM6DtfgznB7Z1BvCik1U9s%2FXUb6tqdE6YjggUg%3D%3D" rel="nofollow">那些你可能不知道的微博奇技淫巧</a></p>
<p><a href="https://link.segmentfault.com/?enc=GE7Dy21uSUCl%2B86diZF5cg%3D%3D.BWnNpMXDJtpoI8GAzkyaWtr2JnNBwN03T1RV2BVgShoKGHYRdlazLb1mq2OdXueNsPGg10g0bIvd%2FB%2FIls3Gxg%3D%3D" rel="nofollow">那些你可能不知道的网易云音乐奇技淫巧</a></p>
<p><a href="https://link.segmentfault.com/?enc=zkkGeJVQ8XnlCoULkx4d7w%3D%3D.fdPSKZAxhBiwgT5O15CcuVoBiuhlG0MagC2EQc873yPxehziOpqT7d4JgX9N%2B8xelC1Pq08X5cuhAeDPOTKlhcw0PhXZyD8eYmL5m7bZdctTBnuJt6qJWIeB0s7QVD4wQKOWf5icc5ZJN53HdZm9%2FEe1EuKVeu1d6vTZSuzWLAFBRSam6DXUI1QQkkGUiYA9lh8tmKS%2FU%2FPseZhsHMXN2A%3D%3D" rel="nofollow">那些你可能不知道的搜索奇技淫巧</a></p>
<p><a href="https://link.segmentfault.com/?enc=3ot5bwUDHB4%2FGE0u9WhsZQ%3D%3D.0w9RveEd8oGVbdT2S8POIvoqfs2KenZSwFDKSdS2Zw8%2ByQOwibjc4SxLoWZRYagyq1EAqfYGu6bgsgjaXkfVbt0jxI6SzvPKlBb8d20yQgst01lO6STFOyOAcbg9X6vmDhGenbmvZZxOVNaiHp3N5uqrkAFdCCjZsXkbzVtgle0XlYA1HQ%2Bqn029sBvu%2BhnU%2BcbO4VS%2F64Fu3ymX6fTg534t0jTI5NhdZ7iUbJ0JwZS0NDyVHHguNHw5D0%2BTc1gRukQU6cuYbLz%2FoOLdMXz4lY%2BZs2JIHDVdlMdG%2F87JgcbScazo5gTZ9%2FqM6ZXCKMmayA9O4TAO91Tw%2BNgc%2FfwykA%3D%3D" rel="nofollow">那些你可能不知道的视频下载奇技淫巧</a></p>
<p><a href="https://link.segmentfault.com/?enc=tpOWrJ31oqc7%2BlSqvRJ%2Bhg%3D%3D.gbOQQXdPomxsez2mpxqPWBuIyKxFzbZ2OZ5ikO5M%2BygGw2O86Cxd53VGWb7PVyxDVQoglnUDeV1kdoriorAEcw%3D%3D" rel="nofollow">那些你可能不知道的免费观看 VIP 视频奇技淫巧</a></p>
<p><a href="https://link.segmentfault.com/?enc=D0l8Qv5CU%2BWicFdeJUFXXA%3D%3D.Jbctgh2cMKuDnc4TaHDKTUZ3DjLFFAOq7XDGxr3OAX7YYKm6gCxAI%2FtYN726KRr%2FTM3hF0UkI5ZoToHobQXMhA%3D%3D" rel="nofollow">那些你可能不知道的知乎奇技淫巧</a></p>
<p><img src="/img/remote/1460000019754928" alt="免费星球" title="免费星球"></p>
<h3>公众号:苏生不惑</h3>
<p><img src="/img/remote/1460000019152534" alt="扫描二维码关注" title="扫描二维码关注"></p>
命令行录制工具 asciinema
https://segmentfault.com/a/1190000019713172
2019-07-09T20:05:55+08:00
2019-07-09T20:05:55+08:00
苏生不惑
https://segmentfault.com/u/sushengbuhuo
11
<p>平常出bug求助的时候有时候贴代码或者截图往往不直观,如果能重现给对方看就好了,这里推荐 2 个命令行的录制工具。</p>
<h3>asciinema</h3>
<p>网站<code>https://asciinema.org/ </code>,github主页<a href="https://link.segmentfault.com/?enc=ON%2B0N6S%2FQuHqZjNOJJ0ZFQ%3D%3D.0dyy1qjH95HPNg8hvAdT9xXnzND45AAU7L21zcSC%2FVw%3D" rel="nofollow">https://github.com/asciinema</a> <br>直接使用 <code>pip install asciinema </code>来安装。<br> 执行<code>asciinema rec</code> 开始录制,录制完成后 exit 退出,可以保存到本地或者上传到 <code>https://asciinema.org</code> 。</p>
<pre><code class="js">[root@VM_0_14_centos ~]# asciinema rec
asciinema: recording asciicast to /tmp/tmp1ua5a2rx-ascii.cast
asciinema: press <ctrl-d> or type "exit" when you're done
[root@VM_0_14_centos ~]# pwd
/root
[root@VM_0_14_centos ~]# cd /usr/share/nginx/html/
[root@VM_0_14_centos html]# pip install asciinema
DEPRECATION: Python 3.4 support has been deprecated. pip 19.1 will be the last one supporting it. Please upgrade your Python as Python 3.4 won't be maintained after March 2019 (cf PEP 429).
Looking in indexes: http://mirrors.tencentyun.com/pypi/simple
Requirement already satisfied: asciinema in /usr/lib/python3.4/site-packages (2.0.2)
You are using pip version 19.0.3, however version 19.1.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
[root@VM_0_14_centos html]# pip list |grep ascii
DEPRECATION: Python 3.4 support has been deprecated. pip 19.1 will be the last one supporting it. Please upgrade your Python as Python 3.4 won't be maintained after March 2019 (cf PEP 429).
asciinema 2.0.2
You are using pip version 19.0.3, however version 19.1.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
[root@VM_0_14_centos html]# exit
exit
asciinema: recording finished
asciinema: press <enter> to upload to asciinema.org, <ctrl-c> to save locally
View the recording at:
https://asciinema.org/a/AdnqMX0QfOg5c7USOtwHZ4Hz1
This installation of asciinema recorder hasn't been linked to any asciinema.org
account. All unclaimed recordings (from unknown installations like this one)
are automatically archived 7 days after upload.
If you want to preserve all recordings made on this machine, connect this
installation with asciinema.org account by opening the following link:
https://asciinema.org/connect/01fb0f0e-c56a-450f-80ac-4020188dd957</code></pre>
<p>录制过程在<a href="https://link.segmentfault.com/?enc=wCBB6bUI5GjuXb3CYmv4SQ%3D%3D.elSSdFr62d4Fb469qQexsdKQlJOazMGq4cOczvN4gELM36ArCHW1U1trJkeT46rk%2F5JI1hLztJ4ErJ5kPris2g%3D%3D" rel="nofollow">https://asciinema.org/a/AdnqM...</a> 可以看到了。</p>
<p><img src="/img/bVbuSsb?w=918&h=484" alt="clipboard.png" title="clipboard.png"></p>
<p>如果分享给他人可以用邮箱注册,它不需要密码就可以注册。我注册后的主页<a href="https://link.segmentfault.com/?enc=buTqaQypDVBlvXgsDzFUmw%3D%3D.epYjWQMsmKrGhL6VzydRAPuRgxkjA8Be8Ojj2keXT%2B8%3D" rel="nofollow">https://asciinema.org/~susheng</a><br>然后打开这个链接 <a href="https://link.segmentfault.com/?enc=iz1A7%2Fn%2FuUHZ7CuC0eNMTg%3D%3D.CG%2FpjNReJI7eptxEGXR%2B%2FhGA4psbm99dM%2BtHO4h%2FxYDcfvJPKW0T34xB8msGiRTvcFiSm9bjwbehahv%2BedAqf0NRS8abE1F0X1l%2BBoxrP0o%3D" rel="nofollow">https://asciinema.org/connect...</a> 就会保存到你账号下。</p>
<p><img src="/img/bVbuSsd?w=546&h=541" alt="clipboard.png" title="clipboard.png"></p>
<p>设置为public 后可生成公开链接,可分享给他人观看,还可以嵌入到自己的网站。</p>
<p><img src="/img/bVbuSse?w=1063&h=574" alt="clipboard.png" title="clipboard.png"></p>
<p><img src="/img/bVbuSsj?w=794&h=543" alt="clipboard.png" title="clipboard.png"></p>
<p>视频链接后加 .png 是视频截图 <a href="https://link.segmentfault.com/?enc=m6w1FglCdsNXwYWVyy%2FMzg%3D%3D.4L7LlNPgUmmGgq5iLdsKejvbY3sy6gr7he9e899aYsPL3nwwElaMAaPVbN2fbS2B" rel="nofollow">https://asciinema.org/a/25434...</a> ,而链接后加 .js 就可以直接嵌入网站了。</p>
<pre><code class="js"><a href="https://asciinema.org/a/254348" target="_blank"><img src="https://asciinema.org/a/254348.svg" /></a>
<script src="https://asciinema.org/a/254348.js" id="asciicast-254348" async data-autoplay="true" data-size="big"></script></code></pre>
<h3>TermRecord</h3>
<p>TermRecord也是用 pip 安装 <code>pip install TermRecord</code>, 直接开始录制 <code>TermRecord -o termrecord.html </code>输入 exit 结束录制 。这个 termrecord.html 就是录制生成的文件,可以直接用浏览器打开。</p>
<pre><code class="js">[root@VM_0_14_centos html]# TermRecord -o termrecord.html
Script started, file is /tmp/tmpdekpz_p2
[root@VM_0_14_centos html]# pwd
/usr/share/nginx/html
[root@VM_0_14_centos html]# whoami
root
[root@VM_0_14_centos html]# pip install TermRecord
DEPRECATION: Python 3.4 support has been deprecated. pip 19.1 will be the last one supporting it. Please upgrade your Python as Python 3.4 won't be maintained after March 2019 (cf PEP 429).
Looking in indexes: http://mirrors.tencentyun.com/pypi/simple
Requirement already satisfied: TermRecord in /usr/lib/python3.4/site-packages (1.2.5)
Requirement already satisfied: Jinja2>=2.6 in /usr/lib64/python3.4/site-packages (from TermRecord) (2.10.1)
Requirement already satisfied: MarkupSafe>=0.23 in /usr/lib64/python3.4/site-packages (from Jinja2>=2.6->TermRecord) (1.1.1)
You are using pip version 19.0.3, however version 19.1.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
[root@VM_0_14_centos html]# pip list|grep Term
DEPRECATION: Python 3.4 support has been deprecated. pip 19.1 will be the last one supporting it. Please upgrade your Python as Python 3.4 won't be maintained after March 2019 (cf PEP 429).
TermRecord 1.2.5
You are using pip version 19.0.3, however version 19.1.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
[root@VM_0_14_centos html]# exit
exit
Script done, file is /tmp/tmpdekpz_p2</code></pre>
<p>然后打开文件就可以看到录制过程了</p>
<p><img src="/img/bVbuSsp?w=1129&h=537" alt="clipboard.png" title="clipboard.png"></p>
<p>另外还有个基于ruby的showterm和termtosvg就不演示了 <a href="https://link.segmentfault.com/?enc=ZwEjxD0kvz1Ubu2xU0mbrg%3D%3D.hP9cigbthIB73RIz2vbFRMGf34HDgVYGMKhQC11QUGE%3D" rel="nofollow">http://showterm.io/</a> <br><a href="https://link.segmentfault.com/?enc=UXsvjM9vBmaHpHHL5KJ2Vg%3D%3D.19G9XS3cIMOIEEdvSv427vipvsmDdN1vpNtVJdRstTdQubFwkNs0BL4sUfSZxyrw" rel="nofollow">https://github.com/nbedos/termtosvg</a></p>
<p>推荐阅读:</p>
<p><a href="https://link.segmentfault.com/?enc=7j3IXPtmQvJ419V5oY7iug%3D%3D.cAu9i8mn2PyvZccAlJGMdXYUIdgyZBoP354j0WAOkOar479oU6Sj%2F3JGE6VESL6Wv7xsd2yfnoH73bijZIwDAw%3D%3D" rel="nofollow">那些你可能不知道的浏览器奇技淫巧</a></p>
<p><a href="https://link.segmentfault.com/?enc=A%2F3t4kl11EPiXFBSZ1gyVQ%3D%3D.EGkZZsKQvqwvHkoDVPy5CbVo6EJc90ncW5JlU7CWYyWX0rQKmZuJM4kwCjlp6yYzWT%2FFZTsX1iPTjHfbXm2T8A%3D%3D" rel="nofollow">那些你可能不知道的微信奇技淫巧</a></p>
<p><a href="https://link.segmentfault.com/?enc=O7bGThrKIHvw60egz%2FLeIQ%3D%3D.fO%2B%2FAKWjrr3q23F7V7ZLE%2BPtFh3DPsqGz6MZJF2ZR2w7oeW0YUR%2BAUI8Wbjd9q%2BT2H1xvPqh1eABC%2FUCDgEvCQ%3D%3D" rel="nofollow">那些你可能不知道的微博奇技淫巧</a></p>
<p><a href="https://link.segmentfault.com/?enc=SWhFbSE7w7GyAL%2FgBfRObQ%3D%3D.1zbq4b1MsUpOTxaVxF6Rd4Mexi%2F58k11OcjHTQnNvs9snNGz4fBW2st7uEhAMXIgJIAJzGSKdW2crTqPzEhTtw%3D%3D" rel="nofollow">那些你可能不知道的网易云音乐奇技淫巧</a></p>
<p><a href="https://link.segmentfault.com/?enc=AY1ZVt5RtUsBDCDqHKCstg%3D%3D.OmZhX%2B6OwUBVO%2B%2FI0zBIq9WAtSqfcgTtccH06FqNz7AwWanUjo12frjl525gaoKrysLt9QKbiiOuyNpHQzItemPkXhSsE3rNR2SbXdT0rY1D3cSGtDHID0y1D1G1Nq7EWLe5dc8UBHnnk4w94s%2BQyU2enjZ%2FlUhXgvwDjnanJSBbfCcCTf9ugh3TdpVAX%2F%2FjetEURJG0A5adxxUl9olTLg%3D%3D" rel="nofollow">那些你可能不知道的搜索奇技淫巧</a></p>
<p><a href="https://link.segmentfault.com/?enc=2jqmcloFW7coz6p3deg9Pg%3D%3D.npxs8EyMBjt3H4VcG6dSBf9sV4jneU1M1vgcHnocw7y0qG%2BGF3ET%2BoiPF2YUhu2RYXI0zcz9soM5t%2F2bRZkVHifrhfK%2F6mV3J4ya%2F%2BKw8%2BhUvhh9DtyRfcoG5pL01L%2FIT03ngWClYwgdUQNWR1pqhHuz6h1vSR6JjPRlQ44dyH66lM8TUtscwCIUGrJcxvhYSiRRO5krLu9n0Sdq77szrU4NkW1YtP0QG9iAa%2B6V9rJ9rqxYFbMooKxC9rr2pXGDKk7dJ9WkTyw4i%2FlyaCsoGinmdk36gcgZonhBNeytOPnNQHEbxYM00lDgYRApnvoJnNHN65EmTF17CVbTxJTCDw%3D%3D" rel="nofollow">那些你可能不知道的视频下载奇技淫巧</a></p>
<p><a href="https://link.segmentfault.com/?enc=SRKjJO8NLsUxbSSZlGU7NQ%3D%3D.bcjTwQh3QANWvWdi%2FzMklCMBudXPNfJNbW1gMQBGcsCH%2BA1Fxil0cpq7d8jvVvsTvARpGQ%2B8OYXWDywZkSI2OA%3D%3D" rel="nofollow">那些你可能不知道的免费观看 VIP 视频奇技淫巧</a></p>
比 man 更强悍的命令行工具 cheat
https://segmentfault.com/a/1190000019616139
2019-06-29T10:20:58+08:00
2019-06-29T10:20:58+08:00
苏生不惑
https://segmentfault.com/u/sushengbuhuo
22
<p>经常使用命令行,比如 curl 测试接口响应时间</p>
<pre><code class="js">for i in {1..10};do curl -o /dev/null -s -w "$i | time_namelookup: %{time_namelookup} | time_connect: %{time_connect} | time_starttransfer: %{time_starttransfer} | time_total: %{time_total}\n" "http://httpbin.org/ip";done
1 | time_namelookup: 0.016000 | time_connect: 0.016000 | time_starttransfer: 0.125000 | time_total: 0.141000
2 | time_namelookup: 0.016000 | time_connect: 0.016000 | time_starttransfer: 0.094000 | time_total: 0.109000
3 | time_namelookup: 0.016000 | time_connect: 0.031000 | time_starttransfer: 0.109000 | time_total: 0.109000
4 | time_namelookup: 0.015000 | time_connect: 0.031000 | time_starttransfer: 0.109000 | time_total: 0.109000
5 | time_namelookup: 0.031000 | time_connect: 0.031000 | time_starttransfer: 0.109000 | time_total: 0.109000
6 | time_namelookup: 0.016000 | time_connect: 0.016000 | time_starttransfer: 0.094000 | time_total: 0.109000
7 | time_namelookup: 0.016000 | time_connect: 0.016000 | time_starttransfer: 0.125000 | time_total: 0.125000
8 | time_namelookup: 0.000001 | time_connect: 0.016000 | time_starttransfer: 0.141000 | time_total: 0.141000
9 | time_namelookup: 0.015000 | time_connect: 0.015000 | time_starttransfer: 0.093000 | time_total: 0.109000
10 | time_namelookup: 0.000001 | time_connect: 0.015000 | time_starttransfer: 0.109000 | time_total: 0.125000</code></pre>
<p>奈何命令行参数太多,记不住怎么办?这时候你需要个男人,它就是 man</p>
<h3>man</h3>
<pre><code class="js">#man curl
curl(1) Curl Manual curl(1)
NAME
curl - transfer a URL
SYNOPSIS
curl [options] [URL...]
DESCRIPTION
curl is a tool to transfer data from or to a server, using one of the supported protocols
(DICT, FILE, FTP, FTPS, GOPHER, HTTP, HTTPS, IMAP, IMAPS, LDAP, LDAPS, POP3, POP3S, RTMP,
RTSP, SCP, SFTP, SMTP, SMTPS, TELNET and TFTP). The command is designed to work without user
interaction.
curl offers a busload of useful tricks like proxy support, user authentication, FTP upload,
HTTP post, SSL connections, cookies, file transfer resume, Metalink, and more. As you will
see below, the number of features will make your head spin!
curl is powered by libcurl for all transfer-related features. See libcurl(3) for details.
URL
The URL syntax is protocol-dependent. You'll find a detailed description in RFC 3986.
You can specify multiple URLs or parts of URLs by writing part sets within braces as in:
http://site.{one,two,three}.com
or you can get sequences of alphanumeric series by using [] as in:
ftp://ftp.numericals.com/file[1-100].txt
ftp://ftp.numericals.com/file[001-100].txt (with leading zeros)
ftp://ftp.letters.com/file[a-z].txt</code></pre>
<p>男人的确很强悍,给出了这么多提示,但没有我真正想要的。。。还是不知道怎么用。</p>
<p>相信你在技术文章里经常会看到 TL;DR 即Too Long; Didn’t Read. 太长不看, man curl 的内容就是太长了,我不看。 </p>
<p>就是这个更强壮的男人 tldr,它一个命令行工具,直接使用 <code>npm install -g tldr</code> 来安装。</p>
<h3>tldr</h3>
<pre><code class="js">[root@VM_0_14_centos ~]# npm install -g tldr
/usr/local/n/versions/node/11.4.0/bin/tldr -> /usr/local/n/versions/node/11.4.0/lib/node_modules/tldr/bin/tldr
+ tldr@3.2.7
added 113 packages from 103 contributors in 60.759s
╭───────────────────────────────────────────────────────────────╮
│ │
│ New minor version of npm available! 6.4.1 → 6.9.0 │
│ Changelog: https://github.com/npm/cli/releases/tag/v6.9.0 │
│ Run npm install -g npm to update! │
│ │
╰───────────────────────────────────────────────────────────────╯</code></pre>
<p>安装完后先看看 tldr 自己怎么用吧。</p>
<pre><code class="js">$ tldr tldr
tldr
Simplified man pages.
More information: .
- Get typical usages of a command (hint: this is how you got here!):
tldr command
- Show the tar tldr page for linux:
tldr -p linux tar
- Get help for a git subcommand:
tldr git checkout
</code></pre>
<p>小试牛刀下</p>
<pre><code class="js">$ tldr -p linux tar
tar
Archiving utility.
Often combined with a compression method, such as gzip or bzip.
More information: .
- Create an archive from files:
tar -cf target.tar file1 file2 file3
- Create a gzipped archive:
tar -czf target.tar.gz file1 file2 file3
- Extract an archive in a target directory:
tar -xf source.tar -C directory
- Extract a gzipped archive in the current directory:
tar -xzf source.tar.gz
- Extract a bzipped archive in the current directory:
tar -xjf source.tar.bz2
- Create a compressed archive, using archive suffix to determine the compression program:
tar -caf target.tar.xz file1 file2 file3
- List the contents of a tar file:
tar -tvf source.tar
- Extract files matching a pattern:
tar -xf source.tar --wildcards "*.html"
</code></pre>
<p>嗯,很简洁,直接给出了tar需要的参数,再来看curl</p>
<pre><code class="js">λ tldr curl
curl
Transfers data from or to a server.
Supports most protocols, including HTTP, FTP, and POP3.
- Download the contents of an URL to a file:
curl http://example.com -o filename
- Download a file, saving the output under the filename indicated by the URL:
curl -O http://example.com/filename
- Download a file, following [L]ocation redirects, and automatically [C]ontinuing (resuming) a previous file transfer:
curl -O -L -C - http://example.com/filename
- Send form-encoded data (POST request of type application/x-www-form-urlencoded):
curl -d 'name=bob' http://example.com/form
- Send a request with an extra header, using a custom HTTP method:
curl -H 'X-My-Header: 123' -X PUT http://example.com
- Send data in JSON format, specifying the appropriate content-type header:
curl -d '{"name":"bob"}' -H 'Content-Type: application/json' http://example.com/users/1234
- Pass a user name and password for server authentication:
curl -u myusername:mypassword http://example.com
- Pass client certificate and key for a resource, skipping certificate validation:
curl --cert client.pem --key key.pem --insecure https://example.com</code></pre>
<p>这个男人果然更强悍,常用的curl命令都包括了,我喜欢。</p>
<p>除了自带的命令,安装的命令也可以</p>
<pre><code class="js">[root@VM_0_14_centos ~]# tldr python
python
Python language interpreter.
More information: https://www.python.org.
- Call a Python interactive shell (REPL):
python
- Execute script in a given Python file:
python script.py
- Execute script as part of an interactive shell:
python -i script.py
- Execute a Python expression:
python -c "expression"
- Run library module as a script (terminates option list):
python -m module arguments
- Interactively debug a Python script:
python -m pdb script.py</code></pre>
<p>除了node 还有其他版本 <a href="https://link.segmentfault.com/?enc=mqjoGWIf%2FWoDuM1g4SSk%2BQ%3D%3D.7xFFteqxXBkfse%2FR%2BJ9OHdS49mh9fUmwkayLywombCdaFxZb8QFBAPqVWOKlbIj%2B" rel="nofollow">https://github.com/tldr-pages...</a><br>比如Python,直接pip install tldr安装</p>
<p>如果你不想安装tldr,也可以直接使用网页在线查看<a href="https://link.segmentfault.com/?enc=%2BP8X3I1o4Wwc7V32ohFlTw%3D%3D.9jwAFd7jmkOL4jG0Ef0CpB63k8MIxaups%2BWH7I%2BAJGI%3D" rel="nofollow">https://tldr.sh/</a><br><img src="/img/remote/1460000019616142" alt="image.png" title="image.png"><br> 有了tldr,妈妈再也不用担心我记不住命令行参数了,还有没有比 tldr更强悍的男人呢,有,比如cheat <a href="https://link.segmentfault.com/?enc=nIxR9v%2BVAejFpyoc3OAWRw%3D%3D.vSj%2BVQlrQ2wnyVGNyUhJ%2Fkx%2BguBV0lMpKJztCebeMKI%3D" rel="nofollow">https://github.com/cheat/cheat</a> 直接使用<code>pip install cheat</code>安装。</p>
<h3>cheat</h3>
<p>看看 cheat 怎么用吧</p>
<pre><code class="js">$ cheat cheat
# To see example usage of a program:
cheat <command>
# To edit a cheatsheet
cheat -e <command>
# To list available cheatsheets
cheat -l
# To search available cheatsheets
cheat -s <command>
# To get the current `cheat' version
cheat -v
</code></pre>
<p>试试 curl</p>
<pre><code class="js">$ cheat curl
# Download a single file
curl http://path.to.the/file
# Download a file and specify a new filename
curl http://example.com/file.zip -o new_file.zip
# Download multiple files
curl -O URLOfFirstFile -O URLOfSecondFile
# Download all sequentially numbered files (1-24)
curl http://example.com/pic[1-24].jpg
# Download a file and pass HTTP Authentication
curl -u username:password URL
# Download a file with a Proxy
curl -x proxysever.server.com:PORT http://addressiwantto.access
# Download a file from FTP
curl -u username:password -O ftp://example.com/pub/file.zip
# Get an FTP directory listing
curl ftp://username:password@example.com
# Resume a previously failed download
curl -C - -o partial_file.zip http://example.com/file.zip
# Fetch only the HTTP headers from a response
curl -I http://example.com
# Fetch your external IP and network info as JSON
curl http://ifconfig.me/all/json
# Limit the rate of a download
curl --limit-rate 1000B -O http://path.to.the/file
# Get your global IP
curl httpbin.org/ip
# Get only the HTTP status code
curl -o /dev/null -w '%{http_code}\n' -s -I URL
$ cheat python
# Desc: Python is a high-level programming language.
# Basic example of server with python
# Will start a Web Server in the current directory on port 8000
# go to http://127.0.0.1:8000
# Python v2.7
python -m SimpleHTTPServer
# Python 3
python -m http.server 8000
# SMTP-Server for debugging, messages will be discarded, and printed on stdout.
python -m smtpd -n -c DebuggingServer localhost:1025
# Pretty print a json
python -mjson.tool</code></pre>
<p>比tldr更详细,如果你也不想安装可以直接使用curl</p>
<h3>cht.sh</h3>
<pre><code class="js">[root@VM_0_14_centos ~]# curl cht.sh/curl
# Download a single file
curl http://path.to.the/file
# Download a file and specify a new filename
curl http://example.com/file.zip -o new_file.zip
# Download multiple files
curl -O URLOfFirstFile -O URLOfSecondFile
# Download all sequentially numbered files (1-24)
curl http://example.com/pic[1-24].jpg
# Download a file and follow redirects
curl -L http://example.com/file
# Download a file and pass HTTP Authentication
curl -u username:password URL
# Download a file with a Proxy
curl -x proxysever.server.com:PORT http://addressiwantto.access
# Download a file from FTP
curl -u username:password -O ftp://example.com/pub/file.zip
# Get an FTP directory listing
curl ftp://username:password@example.com
# Resume a previously failed download
curl -C - -o partial_file.zip http://example.com/file.zip
# Fetch only the HTTP headers from a response
curl -I http://example.com
# Fetch your external IP and network info as JSON
curl http://ifconfig.me/all/json
# Limit the rate of a download
curl --limit-rate 1000B -O http://path.to.the/file
# POST to a form
curl -F "name=user" -F "password=test" http://example.com
# POST JSON Data
curl -H "Content-Type: application/json" -X POST -d '{"user":"bob","pass":"123"}' http://example.com
# POST data from the standard in / share data on sprunge.us
curl -F 'sprunge=<-' sprunge.us</code></pre>
<p>看看Python的requests怎么用</p>
<pre><code class="js">[root@VM_0_14_centos ~]# curl cheat.sh/python/requests
# python-requests: Limit Number of Redirects Followed
#
# You have to create Session (http://www.python-
# requests.org/en/latest/api/requests.Session) object and set
# max_redirects variable to 3
session = requests.Session()
session.max_redirects = 3
session.get(url)
# TooManyRedirects exception will be raised if a requests exceeds
# maximum number of redirects.
#
# Related github issue discussing why you can not set max_redirects per
# request https://github.com/kennethreitz/requests/issues/1300
#
# [Alik] [so/q/31552627] [cc by-sa 3.0]</code></pre>
<p>它也有网页版 <a href="https://link.segmentfault.com/?enc=CKFNzUzLqqeY09ddAnCJVA%3D%3D.tjAwm6v6c79iHR9RzrSg%2B4owfchgDqLlItA%2FMdAOzdc%3D" rel="nofollow">http://cht.sh/curl</a><br><img src="/img/remote/1460000019616143" alt="image.png" title="image.png"><br>有了tldr和cheat,再也不用记那么多命令行参数了。</p>
<p>win下我执行命令行的工具是cmder,如果你用的win10,可以尝试下微软最新发布的Terminal <a href="https://link.segmentfault.com/?enc=XH996%2FsA63vR5RDNX0nctg%3D%3D.sTv0KPBkxaVVN%2FR1bAIhBqjKFZznY5jx79%2Fr1URRQShl8uZ%2B6dvsVXtrsWcwr7v6" rel="nofollow">https://github.com/microsoft/...</a></p>
<h3>资源</h3>
<p><a href="https://link.segmentfault.com/?enc=JIMKY%2B%2FZhPOUW3PcpWK88g%3D%3D.pW%2FZRMlp0mmmNClRcumlGmBP3CmewpjaaqTY8kQFQA%2BzKpwHeaSUYnv6qCNWSAR%2B" rel="nofollow">微软最爽命令行工具</a><br><a href="https://link.segmentfault.com/?enc=ZDw2sqACMol4L4k4xmoDJg%3D%3D.GB511H4ePzHoViOoccoSHfHtBcPML%2B7rg6YmTIU0ZtEKAtpm0KQI4%2BZkb0%2B8ZP4y" rel="nofollow">Linux命令大全搜索工具</a><br><a href="https://link.segmentfault.com/?enc=h4p7WYP8YO8%2F7Hgnifa0FQ%3D%3D.j2tPpx%2F7g8u9BPhp7aqsZ%2B%2FPAYfT2RUwL%2Fj0IxQWxIiQioa9e9xA2igqbd9txrHRiRgHDkoRLOUSO9nwNPDiHg%3D%3D" rel="nofollow">Linux工具快速教程</a><br><a href="https://link.segmentfault.com/?enc=VSYlj2GrXzsgY9Fa0LrQGQ%3D%3D.qs0ppaJzzTh%2BKAfLqNRq1g%2FTa%2FQjkjoeOMMTMjO3Wsv94x6MI3iRvfGYYvVwmqxL4VrnaFC6IaZUwtAN%2FEWNYwBj43JdlzBiQu0GIMZLJY3%2Fw35WOwYWaFPVSXIZBW%2B09arMgFWHJUti0gkBr950Dg%3D%3D" rel="nofollow">有趣的Linux命令行工具</a><br><a href="https://link.segmentfault.com/?enc=shdCLXFOfbAl1uCDE3bU6g%3D%3D.zTiQ38MsO4ubkMhcE8MJl4%2FBjJzzkWBC5TxUNTE%2FEXuKQ99KSLCzSm6LqvOTmNG109gUZddoJ0PFnBmFBAaJbKQDbcyFZU%2BflaUc%2BYf0YOg%3D" rel="nofollow">命令行的艺术</a><br><a href="https://link.segmentfault.com/?enc=kFZi4EJHX27gT2zdyy69IA%3D%3D.GpW4ziP0D6z6V8qhw26Vk%2FC88D6zKUEQ1Vzumt%2FNHhqk88FKBL2lq0jGprrDONQE" rel="nofollow">假装很忙的三个命令行工具</a><br><a href="https://link.segmentfault.com/?enc=1DolXmemae1yCdpbVVp8Zw%3D%3D.YzU2EzbnT%2FDPUJ612PePTSyPrlui%2BcKpS%2B00VuldfGtHDmxjSQ%2FEryuOUsU8Wejh" rel="nofollow">28个UNIX/LINUX的命令行神器</a><br><a href="https://link.segmentfault.com/?enc=VqMHTtTzgIWSHFflb%2Fv7qg%3D%3D.yrehnNv749bGDTbDemwTAAs6%2BKf9Dh86zwyrT086I0SkmPeLO9YvzmjRWXTQXxVOsl7AGCb8J5H0Fc%2F5a5kG1YW%2FIpzCh6mToehaY8ck%2F4RIK2XmhkUqEcioMF1LHkEn" rel="nofollow">命令行工具</a><br><a href="https://link.segmentfault.com/?enc=0KyAvf0OCE4uEpsa8joGqA%3D%3D.Krp2CFWHhfyAm%2BODWjMT%2BBya3l9IDF7w%2FLIeldgi5ESy6UJNegf95B4ZY7Q9d96hSsARHX7EYViKfHj2r5dDDA%3D%3D" rel="nofollow">PHPer 必知必会的 Linux 命令</a></p>
<p>推荐阅读:</p>
<p><a href="https://link.segmentfault.com/?enc=QUXHZDYXLyVmfkLHg5oHuA%3D%3D.%2BFoQd%2FHoralltdZDhtlMGa%2Bg3FVxloceZWzYiS68QHJITyup12keCzS%2BKIEtjkd14Aw%2BN7Pyx1N4hyrbtU8SYw%3D%3D" rel="nofollow">那些你可能不知道的浏览器奇技淫巧</a></p>
<p><a href="https://link.segmentfault.com/?enc=NzL%2BfQCOdXw0muSHlMBE2Q%3D%3D.Xz6UP99W6W6ZzaoBGSyiHfiE7IvM1UZFllAx74pBhlUS0%2BAJxNdSsY7baXRwvOjFrS54W4joCsVxjvUhh8bmSA%3D%3D" rel="nofollow">那些你可能不知道的微信奇技淫巧</a></p>
<p><a href="https://link.segmentfault.com/?enc=MsXGDCWUMk0poX%2FbBt0YmA%3D%3D.Mn9eEIeYawSxd83aXTp2jyPp3W15DWo%2BOhfRd7HYYI%2FL81d8o1kJJFHwUhGu9zW1FIxHu9vh13EYMY0E7lDszw%3D%3D" rel="nofollow">那些你可能不知道的微博奇技淫巧</a></p>
<p><a href="https://link.segmentfault.com/?enc=4AA8MbuQ7mrNcJYIL5MdXA%3D%3D.yY07%2FmIPMTcGDvM1Bba7ZV891rwZ9owrY6RNX5BJbl4oQDRhMexV43Dh0Oo1b%2BbCnDfAmuKvEwOpauRX3WqZKw%3D%3D" rel="nofollow">那些你可能不知道的网易云音乐奇技淫巧</a></p>
<p><a href="https://link.segmentfault.com/?enc=a9itlVCWYWpum3ZJOsMeQg%3D%3D.LhW6T%2Fwyw4KoYovXK43zrrC8hk7EKEpmsK7PlT%2FF3u4HkhUoikQIZsAb2dIR0ZufGeL5hRMndcbb3JTA%2Bc5Az%2BlQLEhGrIGpLGWFPpmRGFzT8sXoPGXz90XYhDCBbly3DXsYg5DwAWzMeJ7TaeaaEt725lVSYZaVkdubGpKxsq8iS%2BxqYcPXznM0%2Fuxuhr7bS9zw4V6Qo%2F%2FzrEyURMjuXw%3D%3D" rel="nofollow">那些你可能不知道的搜索奇技淫巧</a></p>
<p><a href="https://link.segmentfault.com/?enc=NStdmZaWXx%2FBVSuvRQsy5w%3D%3D.CQ0x1tcvZQKIhnqoWz3GCpPhSzqfD04mbiu7Etaj3EnLzzCT%2FdRk1RHm5OiOg%2Bx%2BOSwIYZq0Xex%2FAv8aIly4EPw5SmnVnIW0M2JuFj2htUnUCSUAmXk0WP2jYw9CD9x5FyRYB0jFggYPnNBt57eogCO0MIGIZ51d4OSM2WGSFcVcvkssvPWLRwxv9uT3nQ1shDb62HkDRCE0CdhoKH%2BQYdE3aF6keMjWKSG6mYaleeqfhx9n60c2RctC1ap6l5MsXJYOfmY7tDX9iSsH7B12JM08M%2BC7oAbEr3i8J8fm5sJv7TyWBEKW9BYAUqKQQWyzJwrFCCXEvtDW4RX8XWB2ag%3D%3D" rel="nofollow">那些你可能不知道的视频下载奇技淫巧</a></p>
<p><a href="https://link.segmentfault.com/?enc=4luvubwMiQ3OVguFIPAaZA%3D%3D.pIsUQ5wh74UaEv2AP9uUFnnQo5t4gKXsMZDJHdrtC3ssRD0SHME92bfW%2BM5Zes2rXlfUU1JZjFFoAGWEvewi2g%3D%3D" rel="nofollow">那些你可能不知道的免费观看 VIP 视频奇技淫巧</a></p>
<h3>公众号:苏生不惑</h3>
<p><img src="/img/remote/1460000019152534" alt="扫描二维码关注" title="扫描二维码关注"></p>
文档生成器 mkdocs
https://segmentfault.com/a/1190000019360914
2019-06-01T21:27:11+08:00
2019-06-01T21:27:11+08:00
苏生不惑
https://segmentfault.com/u/sushengbuhuo
6
<p>mkdocs 是 Python 一个对 Markdown 非常友好的文档生成器,<a href="https://link.segmentfault.com/?enc=LM0ArOudI3ZtBThdkJw4Gg%3D%3D.QQLPIJZvi6tziRO6TWcrIqb2WV19FbiiO6rFze3XKcOco61FgbfjRe5GWPuqhiV3LA%2BOPDBrmq15CJknfGM9KQ%3D%3D" rel="nofollow">中文文档地址</a></p>
<p>使用 mkdocs 我们可以用md 编写自己的文档,而且可以免费部署到 GitHub 。</p>
<h3>安装</h3>
<p>pip install mkdocs</p>
<h3>使用</h3>
<pre><code class="js">λ mkdocs.exe new mydoc
INFO - Creating project directory: mydoc
INFO - Writing config file: mydoc\mkdocs.yml
INFO - Writing initial docs: mydoc\docs\index.md
λ cd mydoc\
d:\code\mydoc
λ ls
docs/ mkdocs.yml
d:\code\mydoc
λ mkdocs serve
INFO - Building documentation...
INFO - Cleaning site directory
[I 190528 20:32:49 server:296] Serving on http://127.0.0.1:8000
[I 190528 20:32:49 handlers:62] Start watching changes
[I 190528 20:32:49 handlers:64] Start detecting changes
[I 190528 20:33:06 handlers:135] Browser Connected: http://127.0.0.1:8000/</code></pre>
<p><img src="/img/bVbtoLV?w=1214&h=568" alt="clipboard.png" title="clipboard.png"></p>
<h3>编辑</h3>
<p><code>vi docs/index.md</code><br>把 command 改为中文 命令 记得把文件改为 utf8 编码,否则</p>
<pre><code class="js">INFO - Building documentation...
ERROR - Encoding error reading file: index.md
ERROR - Error reading page 'index.md': 'utf-8' codec can't decode byte 0xc3 in position 92: invalid continuation byte
[E 190528 20:38:45 ioloop:801] Exception in callback <bound method LiveReloadHandler.poll_tasks of <class 'livereload.handlers.LiveReloadHandler'>></code></pre>
<p>刷新看到效果</p>
<p><img src="/img/bVbtoLW?w=1065&h=510" alt="clipboard.png" title="clipboard.png"></p>
<p>vi mkdocs.yml <br>把site_name 的 my docs 改为中文 我的文档</p>
<p><img src="/img/bVbtoLX?w=978&h=521" alt="clipboard.png" title="clipboard.png"></p>
<h3>添加页面</h3>
<p>vi about.md <br>vi mkdocs.yml</p>
<pre><code class="js">site_name: 文档
pages:
- [index.md, Home]
- [about.md, About]</code></pre>
<p>然后报错了</p>
<pre><code class="js">INFO - Building documentation...
ERROR - Config value: 'pages'. Error: Invalid pages config. {<class 'list'>} {<class 'str'>, <class 'dict'>}
[E 190529 09:57:45 ioloop:801] Exception in callback <bound method LiveReloadHandler.poll_tasks of <class 'livereload.handlers.LiveReloadHandler'>>
Traceback (most recent call last):
File "d:\python\lib\site-packages\tornado\ioloop.py", line 1229, in _run
return self.callback()
File "d:\python\lib\site-packages\livereload\handlers.py", line 69, in poll_tasks
filepath, delay = cls.watcher.examine()
File "d:\python\lib\site-packages\livereload\watcher.py", line 105, in examine
func()
File "d:\python\lib\site-packages\mkdocs\commands\serve.py", line 107, in builder
site_dir=site_dir
File "d:\python\lib\site-packages\mkdocs\config\base.py", line 210, in load_config
"Aborted with {0} Configuration Errors!".format(len(errors))
mkdocs.exceptions.ConfigurationError: Aborted with 1 Configuration Errors!
λ mkdocs -V
mkdocs, version 1.0.4 from d:\python\lib\site-packages\mkdocs (Python 3.7)</code></pre>
<p><img src="/img/bVbtoL1?w=1062&h=674" alt="clipboard.png" title="clipboard.png"></p>
<p>查找到issue <a href="https://link.segmentfault.com/?enc=Sm6J6Og7Wh9jx2dmk5NCPA%3D%3D.IYfwWWPiEP5P%2Fi%2FIGOEJqTX5Uukny5EN6jGhqnLipjz22WjJKhbLz3ZXgCeinkbG" rel="nofollow">https://github.com/mkdocs/mkd...</a><br><a href="https://link.segmentfault.com/?enc=ALCJGRbmgS84cHAvY3Qthg%3D%3D.XxQHwJwWfodRgRmu6s7e56JtQUkXiWYDzYUSz3n%2FAQizMED5TXSs6sORp6LRVaqcQa7R8dYNlWaP%2BjRYoUAIdLHIggndAotAVlCHzf3uler9G%2FUdNoQbyOAgek4KbNaC" rel="nofollow">https://www.mkdocs.org/user-g...</a> <br>改为</p>
<pre><code class="js">site_name: 我的文档
nav:
- 主页: 'index.md'
- 关于: 'about.md'
theme: readthedocs</code></pre>
<p><img src="/img/bVbtoL2?w=1116&h=689" alt="clipboard.png" title="clipboard.png"></p>
<p><a href="https://link.segmentfault.com/?enc=NQ4DIiTxbchSuq%2BHbP3ZLg%3D%3D.i557eJkAprrItQY6PkJdGFbAoAW0dI9csmgSZPO9C8CJnp%2FUCp5ymUN6%2FHHI0mz%2FhlDJDPDSCY08SHkjxx%2Fv9Q%3D%3D" rel="nofollow">https://markdown-docs-zh.readthedocs.io/zh_CN/latest/</a></p>
<p>原来是中文文档过时了。</p>
<h3>生成秘钥</h3>
<p>cd ~/.ssh<br>ssh-keygen -t rsa -C “mysusheng@gmail.com”<br>这里不要一路回车,我们自己手动填写保存路径<br>vi config</p>
<pre><code class="js">Host github.com
HostName github.com
User git
IdentityFile ~/.ssh/mysusheng
λ ssh -T git@github.com
Hi sushengbuhuo! You've successfully authenticated, but GitHub does not provide shell access.</code></pre>
<h3>站点生成</h3>
<pre><code class="js">λ mkdocs build
INFO - Cleaning site directory
INFO - Building documentation to directory: d:\code\mydoc\site
d:\code\mydoc
λ ls
docs/ mkdocs.yml site/</code></pre>
<p>一段时间后, 可能有文件被从源码中移除了, 但是相关的文档仍残留在 site 目录中. 在构建命令中添加 --clean 参数即可移除这些文档.</p>
<pre><code class="js">$ mkdocs build --clean
λ cd site\
d:\code\mydoc\site
λ ls
404.html css/ img/ js/ search.html sitemap.xml.gz
about/ fonts/ index.html search/ sitemap.xml
d:\code\mydoc\site
λ php -S localhost:8000
PHP 7.1.13 Development Server started at Wed May 29 10:17:19 2019
Listening on http://localhost:8000</code></pre>
<h3>部署到GitHub</h3>
<pre><code class="js">λ git clone https://github.com/sushengbuhuo/markdown_doc
Cloning into 'markdown_doc'...
remote: Enumerating objects: 3, done.
remote: Counting objects: 100% (3/3), done.
remote: Total 3 (delta 0), reused 0 (delta 0), pack-reused 0
Unpacking objects: 100% (3/3), done.
d:\code
λ cd markdown_doc\
d:\code\markdown_doc (master)
λ ls
README.md
d:\code\markdown_doc (master)
λ mkdir docs
d:\code\markdown_doc (master)
λ cd docs\
d:\code\markdown_doc\docs (master)
λ mkdocs.exe new .
INFO - Writing config file: .\mkdocs.yml
INFO - Writing initial docs: .\docs\index.md
d:\code\markdown_doc\docs (master)
λ mkdocs build
INFO - Cleaning site directory
INFO - Building documentation to directory: d:\code\markdown_doc\docs\site
d:\code\markdown_doc\docs (master)
λ echo "site/" >> .gitignore
d:\code\markdown_doc\docs (master)
λ mkdocs gh-deploy --clean
INFO - Cleaning site directory
INFO - Building documentation to directory: d:\code\markdown_doc\docs\site
WARNING - Version check skipped: No version specificed in previous deployment.
INFO - Copying 'd:\code\markdown_doc\docs\site' to 'gh-pages' branch and pushing to GitHub.
INFO - Your documentation should shortly be available at: https://sushengbuhuo.github.io/markdown_doc/</code></pre>
<p>就是把site目录代码上传到github gh-pages分支了.</p>
<p>浏览器访问 <a href="https://link.segmentfault.com/?enc=83XewjBNfywG%2BootfRbFXg%3D%3D.kFarEXISYURPGPamHNcUvSxD2crj4E%2BPvntrFRnoonyWYzV0G%2Fa8RUdqIudPajfz" rel="nofollow">https://sushengbuhuo.github.i...</a> 看到效果了。</p>
<p><img src="/img/bVbtoNv?w=1073&h=532" alt="clipboard.png" title="clipboard.png"></p>
<h3>资源</h3>
<p><a href="https://link.segmentfault.com/?enc=gMXMyGQAHHHOMBFC5jTG0w%3D%3D.QJDcewj%2FyhQsDP8yBQxJJ%2BhWFbFBrY3A4WzWazDToc78OsIYi%2Bu2DgDogF0yfzE6zSMMZc7TrqBg9pKVcooQZIa4sjIxeuojXQbejKqmqZ8%3D" rel="nofollow">Python 中文数据结构和算法教程</a><br><a href="https://link.segmentfault.com/?enc=99o7FgbsKupaZoa1mOlmUA%3D%3D.qYYrRrsIgYF%2BgRJajvNY1E3CIVmriLTp6yAZPWBMVP%2FY7RNb8FcIlKGf9H74i8no" rel="nofollow">类似gitbook生成文档工具</a><br><a href="https://link.segmentfault.com/?enc=JdmfZhANyEnuKEpxvNlcAg%3D%3D.%2FS%2Fy%2BqoLRXkm5tsKun3y6esdvCJ5N6OaoDJvUC3%2BWJSgkM3nfA55dB9Onc%2FWA2XBR7bNzc2e%2Fvm4t7ee7F2SKw%3D%3D" rel="nofollow">Python Web 入坑指南</a><br><a href="https://link.segmentfault.com/?enc=xLlBN1lzAYXjnSOqpZ4kIw%3D%3D.1t29HwIwkACrwU%2BG7XyCmdT8Gxs8Z4%2F2Z8k1wf8qF0hwnRtQiBpmgw%2BcWU7tNfqoDrnsVJ3vrqn7GMonUkDWXg%3D%3D" rel="nofollow">mkdocs配置</a><br><a href="https://link.segmentfault.com/?enc=1hsZb2d%2FKBGqwCbFeZ7ypA%3D%3D.ba%2BVDIsm9G82kpyOIaMriMVSiZ2ewowdMjCwxPWwXbI%3D" rel="nofollow">文档查询工具</a><br><a href="https://link.segmentfault.com/?enc=XFaiUyP1IHaXgrGs32KIWw%3D%3D.TyCUAjJD9WKLld6tGEt%2Fvi4gGacLbw5z%2FFwZWlldkDM%2BrXRx5ASrDhUEuo%2Fhk3sQTZUQwD9I5MxJ41LLDrQbUyNmW2VVBfdKU7RlprhWbQ0%3D" rel="nofollow">支持数学公式</a><br><a href="https://link.segmentfault.com/?enc=aJQGhNgpCePTbPFAE0MT3A%3D%3D.D7guIvmILuBov%2F4vmf0Lgde8mCWTtuvhRB8DvoXLwLu6vstRueujYG%2BfWzcaFJUD" rel="nofollow">git配置多个SSH Key</a></p>
<h3>公众号:苏生不惑</h3>
<p><img src="/img/remote/1460000019152534" alt="扫描二维码关注" title="扫描二维码关注"></p>
5 分钟使用 hugo 搭建一个自己的博客
https://segmentfault.com/a/1190000019264511
2019-05-22T19:28:07+08:00
2019-05-22T19:28:07+08:00
苏生不惑
https://segmentfault.com/u/sushengbuhuo
2
<p>Hugo是由Go语言实现的静态网站生成器。相比hexo更简单、易用、高效、易扩展、快速部署。</p>
<h2>安装Hugo</h2>
<h3>下载二进制</h3>
<p>进入<a href="https://link.segmentfault.com/?enc=V%2Fkgk9VJ05w24wyjPy1fEg%3D%3D.KWCv09QsIRg52oFJij%2BCpEb2h%2BuYWAdIb5YstwKbyOYIOgyieizr%2FmBzWSt%2Fuqzc" rel="nofollow">github下载地址</a>,选择对应系统的二进制文件,比如我的电脑windows 64位就下载 <a href="https://link.segmentfault.com/?enc=8rMPOJZx5OLobWp10h928g%3D%3D.vKu9pxK50T3tV8vhaaMcExbXxMOm7kFTyIJuzUBC4zuLROaX3ZWBSvFfs0jDWPIAF%2FEr0VC%2BZWnuTuY8ekRgKNax11AKJsLXpUc5XGTSl%2B5VqcILa%2FiTEiWKYZsghKWH" rel="nofollow">hugo_0.55.5_Windows-64bit.zip</a><br><img src="/img/remote/1460000019264514" alt="image.png" title="image.png"></p>
<p>解压出来就是一个EXE文件,加入到环境变量即可</p>
<h3>源码安装</h3>
<p>先安装go,git,设置GOPATH <br>命令行执行 go get -u -v github.com/spf13/hugo,成功后会生成二进制文件</p>
<h2>生成站点</h2>
<p>打开命令行,我使用的是cmder,当然自带的cmd也行。</p>
<pre><code class="js">mkdir blog
cd blog
hugo new site .</code></pre>
<p>目录结构为<br><img src="/img/remote/1460000019264519" alt="image.png" title="image.png"></p>
<h2>编写正文</h2>
<p>使用md语法编辑文件</p>
<pre><code class="js">hugo new hello.md
vi hello.md</code></pre>
<h2>下载主题</h2>
<pre><code class="js">cd themes
git clone https://github.com/spf13/hyde.git</code></pre>
<h2>运行Hugo</h2>
<pre><code class="js">hugo server --theme=hyde --buildDrafts
Building sites …
| EN
+------------------+----+
Pages | 11
Paginator pages | 0
Non-page files | 0
Static files | 6
Processed images | 0
Aliases | 0
Sitemaps | 1
Cleaned | 0
Total in 335 ms
Watching for changes in d:\blog\{content,data,layouts,static,themes}
Watching for config changes in d:\blog\config.toml
Environment: "development"
Serving pages from memory
Running in Fast Render Mode. For full rebuilds on change: hugo server --disableFastRender
Web Server is available at http://localhost:1313/ (bind address 127.0.0.1)
Press Ctrl+C to stop</code></pre>
<p>浏览器里打开: <a href="https://link.segmentfault.com/?enc=HtWpMyLao%2FE7zKf%2FoTjr1w%3D%3D.vkgtkW5UZz384Qv%2BB8IgMSUqL%2FLPfqVfWWRKcU8CdEc%3D" rel="nofollow">http://localhost</a>:1313<br><img src="/img/remote/1460000019264520" alt="image.png" title="image.png"></p>
<h2>部署到github</h2>
<p>在github建立一个repo,比如username.github.io,注意username为自己的用户名,不能为其他的。<br><code>hugo --theme=hyde --baseUrl="http://xxx.github.io/"</code><br>这样静态页面都会生成到 public 目录,将pubilc目录里所有文件 push 到刚创建的Repo的 master 分支就可以了。</p>
<pre><code class="js"> cd public
git init
git remote add origin https://github.com/xxx/xxx.github.io.git
git add .
git commit -m "hugo"
git push -u origin master</code></pre>
<p>打开浏览器访问:<a href="https://link.segmentfault.com/?enc=DqKIPTMlTdbEc1V%2FL%2BxWBg%3D%3D.ZsaI3EVKFGji5lhXA1GDdyCPR0NFI%2FteGaWclGBWKM8%3D" rel="nofollow">http://xxx.github.io/</a></p>
<p>好了,你的博客搭建成功了,开始你的博客之旅吧。<br>公众号:苏生不惑<br><img src="/img/remote/1460000019152534" alt="扫描二维码关注" title="扫描二维码关注"></p>
听说你想 520 表白
https://segmentfault.com/a/1190000019264478
2019-05-22T19:25:49+08:00
2019-05-22T19:25:49+08:00
苏生不惑
https://segmentfault.com/u/sushengbuhuo
2
<p>又到520,一个狂虐单身狗的日子,看看知乎的热门话题:<br><img src="/img/remote/1460000019264481" alt="image.png" title="image.png"></p>
<p>这里给大家提供几个虐狗的新姿势。</p>
<h3>69</h3>
<p>表白从 69 开始,给对方发个网页 <a href="https://link.segmentfault.com/?enc=QLAY%2B43cNs1NdP%2FPa9DUUw%3D%3D.BfvrJvDrXqjsCefu8OdueQKNokQ5rHv7Ugn7%2BNdOBY0xGSpoN6tszNsg%2F9u1Ll4G" rel="nofollow">http://118.24.158.116:8888/loveyou.html</a><br>用浏览器打开,按Ctrl+f 输入9,效果就出来了。<br><img src="/img/remote/1460000019264482" alt="image.png" title="image.png"><br>源码很简单</p>
<pre><code class="js"><script>
document.write("<br><br><br>"+"99669999996669999996699666699666999966699666699"+'<br>'+"99699999999699999999699666699669966996699666699"+'<br>'+"99669999999999999996699666699699666699699666699"+'<br>'+"99666699999999999966666999966699666699699666699"+'<br>'+"99666666999999996666666699666699666699699666699"+'<br>'+"99666666669999666666666699666669966996699666699"+'<br>'+"99666666666996666666666699666666999966669999996"+'<br><br><br><br><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<strong><big></big></strong>');
//键盘按ctrl+f,然后输入9 by@lsp
</script></code></pre>
<h3>表白网页生成器</h3>
<p>打开网站 <a href="https://link.segmentfault.com/?enc=VculB%2B%2FC6qRDicYyJwSsrA%3D%3D.Ijjbuoylx%2Bb5drTKMV7UPF0sP2pkOvCy7f%2B9diJGVAM%3D" rel="nofollow">https://res.luyi.org/love/</a> ,填入要表白的内容:<br><img src="/img/remote/1460000019264483" alt="image.png" title="image.png"><br><a href="https://link.segmentfault.com/?enc=8uDvC1GpeXvPA93sBQMl7A%3D%3D.glslQ4tiKxnXe%2ByHqbeM5OmvSRmusSD8Lcx1DQ4v5Q6kXO4n9JvOe2ZyAf6JhThg3HPesKXjP87uBVmiiJXAovLIU%2F%2B3mMhcmWEnbOXqwlKm2otS%2FEnI4d87MMz9LE3fESioybwLGKI5NTMF4%2FApTiqHkKByEST2SCGCG3FuybwbdLc8eRZuoJyKHPKpTrhDzFmzMfSJKLe%2FkFLqC2%2FNayNUCnLa7YC2BzRQch9qTIpq4g7HPLIxNEvXoOZ%2F0v71RuYZjzF%2FRIZ2G5ymi1ppZeGehljCMzSmSg8plWR%2BfdTtY%2F6yomZxVYVcHkgHczVDxgvOGPDF5TNpNANHe3Qx4mWmXcB0P07N4xII3%2BAfimc%3D" rel="nofollow">生成好的网页</a><br><img src="/img/remote/1460000019264484" alt="image.png" title="image.png"></p>
<h3>百度传情</h3>
<p>其实百度很早就有个传情功能,直接百度输入 表白 即可。<br><img src="/img/remote/1460000019264485" alt="image.png" title="image.png"></p>
<p>输入好对方名字和留言,点击生成爱情密码,可以自定义4-8位密码(不能和别人的重合),也可以随机生成。比如我生成的这个密码数字 20196699,然后让对方百度输入 解蜜20196699 就可以看到你对她的表白了,而且这个网页百度会一直<a href="https://link.segmentfault.com/?enc=WaTmv2uUJ%2FGCynmht7prMQ%3D%3D.IxVbupg9UdJoimwWndAzy2iDWmJiQON9qKJiuT0S9w37PDG6KoO%2Be4XX1hS1IxoGm%2B0rzHiHeNrQPAFF3%2FuHAwCKL9gRwb7peEHbdVy%2BoO0BMP7HA0xGBU4JWCCpoiVzmpCzphO1fdbCjvPPshhQpytzZ4%2FITlcG1oJRAL4PbpK%2BG35pkAHMZsUHMyl1FMapoWQaHYPw1zbdtWouC6E%2BDkAeRzNGZPib1ZSdjZky8GAIJ8cPEZ0nO6Qt1UzfSnq%2B52wGSAePTTk2JrXjYWYseKDftdY4QBqXdJre%2F5qI3SPHL%2Byk0vQ2djdAjrBk%2B%2FKwTKz2qa8EarcEl5dZXCttDGaEAfwXpLvlXqayLIVMEkZHljx6MM5pvC%2BOL%2BLLLyWAPAMZ2F1FqYxIMYqs1C3q6FKZcopgn7wGtPsmzRKaBe4rYjSHSQXutDmdudDL3PT36ATJ%2Bee%2Fqks0g96cSQBLWKn8q6CCeIa5jmI3Y8QwkSOrut2fjfxNEuvX9Equu5svxPSn5pQEUMua%2FMvrJpVkybJU3qIsR4O1LFteKWuQzI8E2k6%2B%2BKt0ZRbUqxtAWkYPp7jY5qTWMDba0DRLZw%2Bt8Q%3D%3D" rel="nofollow">保存着</a></p>
<p><img src="/img/remote/1460000019264486" alt="image.png" title="image.png"></p>
<p>当然如果觉得以上都太虚的话,没事,微信都为你准备好了,每到这一天微信红包提高到 520,记得备好红包!当然首先你得有个女朋友。。。</p>
<h3>公众号:苏生不惑</h3>
<p><img src="/img/remote/1460000019152534" alt="扫描二维码关注" title="扫描二维码关注"></p>
<p><a href="https://link.segmentfault.com/?enc=kEuugX5Bk4ju5TMIipIEbQ%3D%3D.A6217QGxppubBE%2FUSPSxGj%2BRL%2F6Q6bqcbVIyzvyrpX38Rl27Of9gxYZQ2rOn6U6%2F%2BmHDL3bDqglhMtKckduM8w%3D%3D" rel="nofollow">点击阅读公众号原文</a></p>
那些你可能不知道的浏览器奇技淫巧
https://segmentfault.com/a/1190000019264391
2019-05-22T19:16:01+08:00
2019-05-22T19:16:01+08:00
苏生不惑
https://segmentfault.com/u/sushengbuhuo
58
<p>平常工作少不了用浏览器,以下分享一些浏览器的使用技巧,更好的有助于你的工作。</p>
<p>ps: 以下技巧均在 Chrome 浏览器下测试的。</p>
<h3>网页长截图</h3>
<p>按 F12 弹出控制台,按 <code>ctrl+shift+p</code> 弹出输入框<br><img src="/img/remote/1460000019264394" alt="image.png" title="image.png"><br>输入full,选择 <code>capture full size screenshot</code> 然后点击就会对当前网页进图并生成下载一个图片。<br>这个比用 QQ 截图好用的地方就是有滚动条的网页也可以全部截图到,所以叫长截图。<br><img src="/img/remote/1460000019264395" alt="www.google.com.hk_search_newwindow=1&safe=strict&client=aff-maxthon-newtab&channel=t16&source=hp&ei=ll7jXOCENcX68QXZ-pfwBA&q=chrome&oq=chrome&gs_l=psy-ab.12..35i39l2j0i67l3j0i203l5.817.2172..2861...0.0..0.270.855.png" title="www.google.com.hk_search_newwindow=1&safe=strict&client=aff-maxthon-newtab&channel=t16&source=hp&ei=ll7jXOCENcX68QXZ-pfwBA&q=chrome&oq=chrome&gs_l=psy-ab.12..35i39l2j0i67l3j0i203l5.817.2172..2861...0.0..0.270.855.png"></p>
<h3>浏览器秒变编辑器</h3>
<p>浏览器地址栏中输入 <code>data:text/html, <html contenteditable></code>回车直接变编辑器,这里可以直接输入字符进行编辑了。</p>
<p><img src="/img/remote/1460000019264396" alt="image.png" title="image.png"></p>
<h3>编辑网页</h3>
<p>打开网站,地址栏输入<code> javascript:void(document.body.contentEditable='true'); </code>当然也可以直接在控制台输入 <code>document.body.contentEditable=true</code>或<code>document.designMode = "on" </code>然后就可以随心所欲的改变网页内容了,所以一些网页截图不可信,比如之前有人借用王思聪名义用微博发支付宝的红包,可谓套路满满。<br><img src="/img/remote/1460000019264397" alt="image.png" title="image.png"><br><img src="/img/remote/1460000019264398" alt="image.png" title="image.png"></p>
<h3>突破禁止复制</h3>
<p>有些网站是复制不了内容的,比如b站 的文章<a href="https://link.segmentfault.com/?enc=FqUnYd%2BZC2c4KB%2FPn2iAuw%3D%3D.mv3NhJ%2BH0Y1t4GlGciu3q3HDxQBsDKOQnADNjyQRtxXAf8FVxCDrUq8XA%2FnkZXUm0L1DwvJd%2BagRg2K58%2BuyiA%3D%3D" rel="nofollow">https://www.bilibili.com/read/cv2444771?from=category_0</a> ,这个时候就需要用上控制台了(按F12打开)。<br><img src="/img/remote/1460000019264399" alt="image.png" title="image.png"><br>点击左上角箭头,选择网页内容,可以在控制台看到内容,直接复制就行了。<br><img src="/img/remote/1460000019264400" alt="image.png" title="image.png"></p>
<h3>多账号登录</h3>
<p>平常一个浏览器只能登录一个账号,如果要登2个账号,就需要使用多个浏览器,如果只有一个浏览器怎么办,使用隐身模式(按<code>ctrl+shift+n</code>进入),然后登录另外一个账号。<br><img src="/img/remote/1460000019264401" alt="image.png" title="image.png"></p>
<h3>下载网页图片</h3>
<p>想下载网页上的图片,如果一张一张的另存为,那得费不少体力,这个时候就需要控制台了。<br>比如经常逛知乎可以看到不少妹子自拍,比如这个<a href="https://link.segmentfault.com/?enc=mvlDEcr2Ma%2FLW4A2fsB%2FLw%3D%3D.YnuGUUuwJIAx4yVEabhgn9huqBIMn4819MyFrV9oxdD8mqqQ2HT07hnvz83hwysAZ90rxO%2BUUP7X1klppidIsw%3D%3D" rel="nofollow">问题</a><br><img src="/img/remote/1460000019264402" alt="image.png" title="image.png"></p>
<p>打开控制台执行这个</p>
<pre><code class="js">copy($$('img').map(function(item){return item.src}).join("\r\n"))</code></pre>
<p>或者</p>
<pre><code class="js">copy([...$$("img")].map(a => a.src).join('\r\n'))</code></pre>
<p>就可以将所有图片地址复制好了。<br>复制所有链接使用<code>copy($$('a').map(function(item){return item.href;}))</code></p>
<p><img src="/img/remote/1460000019264403" alt="image.png" title="image.png"><br>然后把这些地址放在一个文件<code>url.txt</code>内。<br><img src="/img/remote/1460000019264404" alt="image.png" title="image.png"></p>
<p>接下来用<a href="https://link.segmentfault.com/?enc=iQr37BXQGqv9m45JxV86iw%3D%3D.GAMlPkjMlwJQhkCQCMDZ4lCKgNBPaJ7lPXZZinG39dkNbr%2FkKUkJPBpLaQQzWLCinJBK9ftjK%2BaRPx5fxcfO%2BA%3D%3D" rel="nofollow">wget</a>一键下载。<code>wget -i url.txt -P ./zhihu</code> 所有图片都下载到本地目录zhihu了。<br><img src="/img/remote/1460000019264405" alt="image.png" title="image.png"></p>
<p>另外关于知乎还有个隐藏技能,按<code>?</code>可以打开快捷键帮助,不用鼠标也可以玩知乎了,微博也有这功能。</p>
<p><img src="/img/remote/1460000019264406" alt="image.png" title="image.png"><br><img src="/img/remote/1460000019264407" alt="image.png" title="image.png"></p>
<h3>显示保存密码</h3>
<p>通过审查元素将<code>type=password</code> 的password删掉即可。</p>
<h3>公众号:苏生不惑</h3>
<p><img src="/img/remote/1460000019152534" alt="扫描二维码关注" title="扫描二维码关注"></p>
<p><a href="https://link.segmentfault.com/?enc=2nHdRe4Af5urYmGJZ7IpXg%3D%3D.rBdJo1lXY1a7%2Bug5%2FeMsIyjI%2F3YPD%2BI4D7ZSLzNV9UMoJ%2FmcwSIkU1TrRiVTq5Ymr1DHhPfZhvd%2BdeZF1ZbfRw%3D%3D" rel="nofollow">点击阅读公众号原文</a></p>
ppt 神器 reveal
https://segmentfault.com/a/1190000019152531
2019-05-12T14:31:44+08:00
2019-05-12T14:31:44+08:00
苏生不惑
https://segmentfault.com/u/sushengbuhuo
2
<p>ppt相信大家都用过,不过程序员使用的PPT是可以在网页上用的,比如 reveal</p>
<h2>安装</h2>
<p>先安装好node</p>
<pre><code class="js">npm install -g reveal-md
λ reveal-md -h
Puppeteer unavailable, unable to create featured slide image for OpenGraph metadata.
Puppeteer unavailable, unable to generate PDF file.
Usage: cli <slides.md> [options]
See https://github.com/webpro/reveal-md for more details.
Options:
-V, --version output the version number
--title <title> Title of the presentation
-s, --separator <separator> Slide separator [default: 3 dashes (---) surrounded by two blank lines]
-S, --vertical-separator <separator> Vertical slide separator [default: 4 dashes (----) surrounded by two blank lines]
-t, --theme <theme> Theme [default: black]
--highlight-theme <theme> Highlight theme [default: zenburn]
--css <files> CSS files to inject into the page
--scripts <files> Scripts to inject into the page
--assets-dir <dirname> Defines assets directory name [default: _assets]
--preprocessor <script> Markdown preprocessor script
--template <filename> Template file for reveal.js
--listing-template <filename> Template file for listing
--print [filename] Print to PDF file
--static [dir] Export static html to directory [_static]. Incompatible with --print.</code></pre>
<h2>使用</h2>
<p>vi test.md<br>reveal-md test.md<br>reveal-md slides.md --port 8888<br>浏览器打开localhost:8888 即可在网页上演示PPT了。</p>
<h2>资源</h2>
<p><a href="https://link.segmentfault.com/?enc=5d3hypA%2B0QhVCO9t%2FGpR4g%3D%3D.EV6uRQmwi0sUmxbkgybvaLlPmVQMBNL8HmeKKotXlb%2BonAjkhRlOPVAFD0nV%2B%2FwC" rel="nofollow">reveal-md</a><br><a href="https://link.segmentfault.com/?enc=%2Bj%2FaThEs%2B%2F4Wg1OPlOuBhw%3D%3D.iw5GsSHjMyjvAJl%2BYE7VfkNhdaNpVJbNfIcwUKxkbAPcJFU%2BRNP1RNqvUMB29TB5" rel="nofollow">使用 Jupyter python markdown 制作分享 ppt</a><br><a href="https://link.segmentfault.com/?enc=70%2B9MmL07Jbumr4MgqQsuw%3D%3D.TejM4zCIb8t3EIhTARBktZaa6a0SHgBbmRBPcOAuAmXABXU0eH3r7ynYbWnRy1Dt" rel="nofollow">nodeppt </a></p>
<h2>公众号:苏生不惑</h2>
<p><img src="/img/remote/1460000019152534" alt="扫描二维码关注" title="扫描二维码关注"></p>
ffmpeg 将视频转GIF
https://segmentfault.com/a/1190000018940067
2019-04-21T22:36:33+08:00
2019-04-21T22:36:33+08:00
苏生不惑
https://segmentfault.com/u/sushengbuhuo
7
<p>偶然在b站看了个关于<a href="https://www.bilibili.com/video/av40146374?p=4">FFmpeg的视频</a>,总共10p,花一个多小时就可以学完。学完以后还是挺有意思的,这里做个简单的总结。</p>
<p><img src="/img/bVbrDiJ?w=1026&h=554" alt="clipboard.png" title="clipboard.png"></p>
<p>先准备一个<a href="https://www.bilibili.com/video/av49323758?from=search&seid=11263829590905505159">视频文件</a>,下载到本地就好了。</p>
<h3>播放文件</h3>
<p>ffplay.exe 996之歌.flv <br>播放音频 ffplay 1.mp3</p>
<h3>获取文件属性</h3>
<p>ffprobe 996之歌.flv</p>
<h3>转码mkv为mp4</h3>
<p>ffmpeg -i example.mkv example.mp4</p>
<p>MP4封装:h264视频编码+aac音频编码</p>
<h3>flac转mp3</h3>
<p>ffmpeg -i input.flac -acodec libmp3lame -ar 44100 -ab 320k -ac 2 out.mp3</p>
<pre><code class="js">λ ffmpeg -i "《something just like this》.mp4" -f mp3 outaudio.mp3
ffmpeg version N-93885-gc61d16cf3b Copyright (c) 2000-2019 the FFmpeg developers
built with gcc 8.3.1 (GCC) 20190414
configuration: --enable-gpl --enable-version3 --enable-sdl2 --enable-fontconfig --enable-gnutls --enable-iconv --enable-libass --enable-libdav1d --enable-libbluray --enable-libfreetype --enable-libmp3lame --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-libopus --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libtheora --enable-libtwolame --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxml2 --enable-libzimg --enable-lzma --enable-zlib --enable-gmp --enable-libvidstab --enable-libvorbis --enable-libvo-amrwbenc --enable-libmysofa --enable-libspeex --enable-libxvid --enable-libaom --enable-libmfx --enable-amf --enable-ffnvcodec --enable-cuvid --enable-d3d11va --enable-nvenc --enable-nvdec --enable-dxva2 --enable-avisynth --enable-libopenmpt
libavutil 56. 28.100 / 56. 28.100
libavcodec 58. 52.101 / 58. 52.101
libavformat 58. 27.103 / 58. 27.103
libavdevice 58. 7.100 / 58. 7.100
libavfilter 7. 53.101 / 7. 53.101
libswscale 5. 4.101 / 5. 4.101
libswresample 3. 4.100 / 3. 4.100
libpostproc 55. 4.100 / 55. 4.100</code></pre>
<h3>获取单独的视频流,去除音频</h3>
<p>ffmpeg -i input.mp4 -vcodec copy -an v.mp4</p>
<h3>获取音频</h3>
<p>ffmpeg -i input.mp4 -vn -acodec copy out.m4a</p>
<h3>合并分离的音频和视频</h3>
<p>ffmpeg -i out.m4a -i v.mp4 -c copy out.mp4</p>
<h3>截取前10s</h3>
<p>ffmpeg -i in.mp3 -ss 00:01:00 -to 00:01:10 -acodec copy out.mp3<br>ffmpeg -i in.mp3 -ss 00:01:00 -t 10 -acodec copy out.mp3</p>
<h3>截取末尾10s</h3>
<p>ffmpeg -i in.mp3 -sseof 00:05:00 -t 10 -acodec copy out.mp3<br>ffmpeg -ss 00:01:00 -i in.mp4 -to 00:01:10 -c copy copyts out.mp4 ss在前保证时间戳位置</p>
<h3>合并文件</h3>
<p>ffmpeg -i "concat:01.mp4|02.mp4|03.mp4" -c copy out.mp4</p>
<h3>截图第5s这一帧画面</h3>
<p>ffmpeg -i in.mp4 -ss 5 -vframes 1 img.jpg</p>
<h3>左上角加水印</h3>
<p>ffmpeg -i in.mp4 -i logo.png -filter_complex "overlay=20:20" out.mp4</p>
<h3>7.5到8.5截取成GIF</h3>
<p>ffmpeg -i in.mp4 -ss 7.5 -to 8.5 -s 640x320 -r 15 out.gif</p>
<h3>录屏</h3>
<p>ffmpeg -f gdigrab -i desktop in.mp4</p>
<h3>保持编码下载m3u8</h3>
<p>ffmpeg -i 't.m3u8' -codec copy -y out.ts</p>
<h3>截取片段</h3>
<p>ffmpeg -y -i 'out.ts' -ss 00:01:00 -to 00:10:00 -vcodec copy -acodec copy '1.ts'</p>
<h3>合并ts生成MP4文件</h3>
<p>ffmpeg -y -i "concat:1.ts|2.ts" -map_channel 0.1.0 -map_channel 0.1.0 -s 1024x576 -aspect 16:9 -max_muxing_queue_size 1024 "out.mp4"</p>
<h3>图片转视频</h3>
<p>cat imgs/* |ffmpeg -framerate 1 -i - out.mp4</p>
<h3>m3u8 格式转MP4</h3>
<p>ffmpeg -i "http://xxxxxx/video/movie.m3u8" -vcodec copy -acodec copy -absf aac_adtstoasc output.mp4</p>
<h3>ffprobe 获取一个视频的基本信息</h3>
<p>FFmpeg中常用的工具主要是ffmpeg、ffprobe、ffplay,它们分别用作多媒体的编解码工具、内容分析工具和播放器。 ffprobe 获取一个视频的基本信息,并以JSON格式输出</p>
<p>ffprobe video.mp4 -v quiet -print_format json -show_format -show_streams</p>
<h3>将 gif 转为 mp4</h3>
<p>ffmpeg -f gif -i origin.gif output.mp4</p>
<p><img src="/img/bVbrDkk?w=690&h=432" alt="clipboard.png" title="clipboard.png"></p>
<p><img src="/img/bVbrDku?w=690&h=409" alt="clipboard.png" title="clipboard.png"></p>
<p><img src="/img/bVbrDkB?w=690&h=421" alt="clipboard.png" title="clipboard.png"></p>
<p><img src="/img/bVbrDkA?w=690&h=398" alt="clipboard.png" title="clipboard.png"></p>
<p><img src="/img/bVbrDkm?w=643&h=381" alt="clipboard.png" title="clipboard.png"></p>
<h3>成果</h3>
<p>我将<a href="https://link.segmentfault.com/?enc=%2BoVlSPG9IXdn1MjhNdQ8QA%3D%3D.wWzJVC%2FlJsutBpAd8K85Mx5HkX%2B0j7AiI1vbs91A0l0%3D" rel="nofollow">《在家工作日常》</a> 这个<a href="https://link.segmentfault.com/?enc=5ch9T%2B7n2QfPaYRh%2BFA9sA%3D%3D.clFjBf580b9jCjmeoj4KJkkZ%2FugIsS6rj8MXQXIFvcR1pf%2FgL%2BqZwzPF5RmFd9lnzuGaC6Kh3mFCig3IwLA82InnSzOhQUcRvjd%2FQzF1tYM%3D" rel="nofollow">视频转成GIF</a> </p>
<p><img src="/img/bVbrDkU?w=492&h=253" alt="clipboard.png" title="clipboard.png"></p>
<p><a href="https://link.segmentfault.com/?enc=CitQq0G4P%2BDhhzTHq1gZhA%3D%3D.lhrugOkEiSvTN%2BR%2BRRnMrGE%2BOtZbCfrj%2FJiNV%2FIjNj%2FWj%2BnEcZAX4ejV5%2BozPwFw" rel="nofollow">见微博地址</a></p>
<h3>工具</h3>
<p><a href="https://link.segmentfault.com/?enc=1%2FmlQbEHHi%2FAo55PJh2Avg%3D%3D.mlAQUYkarQIYNpcqfJzromd2EkS82ocSUH6cQm4lA7%2Fspy5mgAStfvRnQGHcqg8yyRopy4eMg0IvlId3%2FFj8rQ%3D%3D" rel="nofollow">视频字幕 </a><br><a href="https://link.segmentfault.com/?enc=36AXZs6vO2H0v9c%2BC%2BAnqA%3D%3D.n5Ed8RiIyyR9VAcub9oSG1YTxt%2FgkNStsNYV0UyLrmNi07KWjBf8c9uypnNXtvfJT%2FeZoNVGaj9766GlM0Ij5g%3D%3D" rel="nofollow">Hardened HLS merger</a><br><a href="https://link.segmentfault.com/?enc=%2F1od11a2%2FKswpbmaSZeujQ%3D%3D.BB5p5eJouIg3BISCdW0LO1w%2Fz%2FzzS2LBqG3jx%2FeC9DCcYH3XGFQQ1iT3mgc0Dd0q" rel="nofollow">Some random notes that I found useful while working with ffmpeg</a><br><a href="https://link.segmentfault.com/?enc=g4z3g9TVZ9%2Fri7DiN1%2FImA%3D%3D.vgMIrj%2BmJedKdNOU8%2Bi05riICEpMRH1GnnjT%2B24%2F1gGX7zWK0srHw34A46qRVXtRnvlkPvoyj%2FwJYuW4oMV4c662vl3VSpFq3Ya8cJ6gck6ZSxT45z5e16qwGhnUh2VxdoIKuX0Vzlk3CRBUen0ajBRpkmDmMAhKG8Ag%2F8LhXK8%3D" rel="nofollow">autosub安装使用指南</a>.html)<br><a href="https://www.bilibili.com/video/av10028738">Final Cut Pro 教程】全系列视频拍摄</a><br><a href="https://link.segmentfault.com/?enc=SywoZBGBEXbOVx8XNEYg8Q%3D%3D.88sVvb28Bw3qnhz84YW9BoBeNy8SK4w2CBI4E1F0AblQJNpJ47I%2FCTmTvSgO4RXx" rel="nofollow">牛逼的视频编辑脚本jumpcutter</a><br><a href="https://link.segmentfault.com/?enc=%2FbT5H7TqEzrHXnkOnAfzkQ%3D%3D.26kT4ECc%2BGyKz2tj7Iz7ZDJ7%2BAXYna5PcYG0Hn%2Bz2ls%3D" rel="nofollow">https://savemedia.com/</a><br><a href="https://link.segmentfault.com/?enc=f3bVbJl9Wy9BpS0EpjxjWQ%3D%3D.GEcxHbLEwh70r59LmW%2BxLC8%2Ft%2FaXchwKkruadEf2zkk%3D" rel="nofollow">https://en.savefrom.net/</a><br><a href="https://link.segmentfault.com/?enc=8c8cCAFGoblWxw8qxP%2BEwQ%3D%3D.l21DDr7xd4rMWa9oMfzpuYLkIcINxKZvQtLtMCq5SBw%3D" rel="nofollow">http://www.clipconverter.cc/</a><br><a href="https://link.segmentfault.com/?enc=Dqqo3egBsf1%2B%2FHoanlNyfQ%3D%3D.LDtsSALTpFRyrSaRVp2z4Z83ylclpzJvaaU3uWHZUEQ%3D" rel="nofollow">http://convert2mp3.net/</a><br><a href="https://link.segmentfault.com/?enc=boXJJIi4PZaj6p3gHmQ9uA%3D%3D.wd%2FrV1%2BsOEi17oZkOK8TFGzloVEWljsJHGfhMHIQapo%3D" rel="nofollow">http://www.downfi.com/video/</a><br><a href="https://link.segmentfault.com/?enc=8VGsEYpr3fOddoLnz5zdRw%3D%3D.5Ou1Wv0FX68%2BLNbgpjiLwPOQXL6ALR5zHuGz%2BSzebJo%3D" rel="nofollow">https://www.soogif.com/video/</a><br><a href="https://link.segmentfault.com/?enc=EqTAULEO2FGyGCT85ZgqqA%3D%3D.thTgFgPbIwuaSLYZQ0Tp%2F2W0jqYjTzgrO4xbwRBddww%3D" rel="nofollow">https://tool.gifhome.com/video/</a><br><a href="https://link.segmentfault.com/?enc=LNKh%2FHn%2Feh9XuHPNwaUbUg%3D%3D.hqSc5mot9%2FFErmcCuYwvTGJ7xb4dN2kcL1bPNfyYJWATW8PuDFe8wKFPJSgBEzeQ" rel="nofollow">https://weibo.com/5198011111/...</a> <br><a href="https://link.segmentfault.com/?enc=LbOkSbJHu0o6kvenubLtYQ%3D%3D.kTw5zI%2BNypjlU%2BjMGFRmdw9jkiv%2BVG0J%2FPm66M0YI7o%3D" rel="nofollow">https://ezgif.com/</a><br>ACONVERT.COM <br><a href="https://link.segmentfault.com/?enc=4ypGN%2BkjRWr1%2FZVzcZFwEw%3D%3D.UJME9xOefJKrxNCNbNOqYLfVDeGjBQXu7B3Vh6ITKmXAR%2B5pJMZkZpVg4Dj2pcIz" rel="nofollow">压缩图片</a> <br>Chrome 插件 MakeGIF Video Capture <br><a href="https://link.segmentfault.com/?enc=8KxjrwKQAIVZ%2BGZgryeHng%3D%3D.K9Wq5PQmivlqqoThRJrOgKXSF%2BNjsHduEnSDKaHsaJI%3D" rel="nofollow">字幕制作神器「Arctime」</a><br><a href="https://segmentfault.com/a/1190000000689321">PHP+FFMPEG自动转码H264标准Mp4文件</a><br><a href="https://segmentfault.com/a/1190000002502526/">ffmpeg命令行转压视频</a><br><a href="https://link.segmentfault.com/?enc=bCkjwWpypFeIIAdSzJP9xg%3D%3D.pUk5YlU51Tx9ZWjOMjHSc6n%2Ffxhba05QzjF9GaTRHozkBZ1w6ERum1YGQGhQ7WrHPTUL77bTauoQKJXe5%2BBlcSa%2FlV8vFR2ScK1O59l3KDUMFMpC3KFOD7W6SHAn%2F2uwISJkfnpIa67PczgyB0Wn4A%3D%3D" rel="nofollow">FFprobe使用指南</a><br><a href="https://link.segmentfault.com/?enc=cDVecHqKYbJoDhmDzDJ0hA%3D%3D.CrFS%2BkDZOdeup6xf1ZlAoh3SU8ltUK9KkHoSyOPPMtg0AjTuThDYBjeL47MNItIp" rel="nofollow">FFmpeg工具使用及参数说明</a><br><a href="https://link.segmentfault.com/?enc=69WdZ%2BrgBSE9ItklV2G%2Fmg%3D%3D.Ol27PCddW%2BUjrOC%2F20cyyJ6uPMF1uJk7fIJ9EUv3k8r8K1lEXgsYLndyETk4QAtp3z9K9%2BoFpBIA%2FkhEMzRLG01JRrJCGMXqCX%2B3UVNZXnE%3D" rel="nofollow">每天学习一个命令:ffprobe 查看多媒体信息</a><br><a href="https://link.segmentfault.com/?enc=0a4psCw%2FU4A%2B5Tojwr9M0Q%3D%3D.r90KkKczVKIi0NpeeSZP%2BJN5VGdcg1EayKwVAaCopS7fsnT6jm0vj6uxeSkBVYnHXkIA6%2FwNzJHgVZ9VF8VFVQ%3D%3D" rel="nofollow">ffmpeg 入门笔记 </a><br><a href="https://link.segmentfault.com/?enc=Z1GdD3cVNU8Z8q6gf8eHGA%3D%3D.tq9cfADDDQS0KF4DP7vwgX9pWovSwXMbDxWad7n7OTVn68gkmHRYAE33zTROt4VD2Kl54xfpLIE70LaXNcOkyDIEwpKlTWG%2BCPThfMnYoCrmyyXMX3jBVu%2BXaXHzMq9ptptdcNQPmxx0OtJ5AJWMDybrujUtyoB2YhXtop9ox%2B3nMaXO0ZAUhaJ%2B1uVFniKZwqQOpNhQtSGl3COOFpy0hA%3D%3D" rel="nofollow">如何使用 FFmpeg 进行视频转码</a><br><a href="https://link.segmentfault.com/?enc=yRt3Ag24eDKA4UCxLFSZnA%3D%3D.%2Bmz9ifg4rs9mTgdfw08qbstsYNwVxC%2BGw1WBrhX7fUkNsLgRpmERqus9vqLIHbdt" rel="nofollow">ffmpeg视音频编解码入门</a><br><a href="https://link.segmentfault.com/?enc=iUXU27ODev7ckDaGPIdMGA%3D%3D.G7zMZpEe2JJFgx5XHFE8SeWZYGneNOmH3j2D9Es7ILoH0rR1ztJ0wKH9VCWLETQ0" rel="nofollow">MP4/FLV格式视频音频在线提取工具</a></p>
laravel cache get 是如何调用的?
https://segmentfault.com/a/1190000017805524
2019-01-08T13:00:00+08:00
2019-01-08T13:00:00+08:00
苏生不惑
https://segmentfault.com/u/sushengbuhuo
4
<p>本文使用版本为laravel5.5</p>
<h3>cache get</h3>
<pre><code class="js">public function cache()
{
$c=\Cache::get('app');
if(!$c) {
\Cache::put('app', 'cache', 1);
}
dump($c);//cache
}
</code></pre>
<h3>config/app.php</h3>
<pre><code class="js"> 'aliases' => [
'App' => Illuminate\Support\Facades\App::class,
'Artisan' => Illuminate\Support\Facades\Artisan::class,
'Auth' => Illuminate\Support\Facades\Auth::class,
'Blade' => Illuminate\Support\Facades\Blade::class,
'Broadcast' => Illuminate\Support\Facades\Broadcast::class,
'Bus' => Illuminate\Support\Facades\Bus::class,
'Cache' => Illuminate\Support\Facades\Cache::class,
]</code></pre>
<p>使用cache实际调用的是<code>Illuminate\Support\Facades\Cache</code>,这个映射是如何做的?</p>
<h3>public/index.php</h3>
<pre><code class="js">$response = $kernel->handle(
$request = Illuminate\Http\Request::capture()
);</code></pre>
<h3>bootstarp/app.php</h3>
<pre><code class="js">$app->singleton(
Illuminate\Contracts\Http\Kernel::class,
App\Http\Kernel::class
);</code></pre>
<h3>app/http/kernel.php</h3>
<pre><code class="js">use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
}</code></pre>
<h3>Illuminate/Foundation/Http/Kernel.php</h3>
<pre><code class="js">public function handle($request)
{
try {
$request->enableHttpMethodParameterOverride();
$response = $this->sendRequestThroughRouter($request);
} catch (Exception $e) {
$this->reportException($e);
$response = $this->renderException($request, $e);
} catch (Throwable $e) {
$this->reportException($e = new FatalThrowableError($e));
$response = $this->renderException($request, $e);
}
$this->app['events']->dispatch(
new Events\RequestHandled($request, $response)
);
return $response;
}
protected function sendRequestThroughRouter($request)
{
$this->app->instance('request', $request);
Facade::clearResolvedInstance('request');
$this->bootstrap();
return (new Pipeline($this->app))
->send($request)
->through($this->app->shouldSkipMiddleware() ? [] : $this->middleware)
->then($this->dispatchToRouter());
}
public function bootstrap()
{
if (! $this->app->hasBeenBootstrapped()) {
$this->app->bootstrapWith($this->bootstrappers());
}
}</code></pre>
<h3>Illuminate/Foundation/Application.php</h3>
<pre><code class="js">public function bootstrapWith(array $bootstrappers)
{
$this->hasBeenBootstrapped = true;
foreach ($bootstrappers as $bootstrapper) {
$this['events']->fire('bootstrapping: '.$bootstrapper, [$this]);
$this->make($bootstrapper)->bootstrap($this);
$this['events']->fire('bootstrapped: '.$bootstrapper, [$this]);
}
}</code></pre>
<h3>Illuminate/Foundation/Bootstrap/RegisterFacades.php</h3>
<pre><code class="js">public function bootstrap(Application $app)
{
Facade::clearResolvedInstances();
Facade::setFacadeApplication($app);
//将config/app.php 里的aliases数组里面的Facades类设置别名
AliasLoader::getInstance(array_merge(
$app->make('config')->get('app.aliases', []),
$app->make(PackageManifest::class)->aliases()
))->register();
}</code></pre>
<h3>Illuminate/Foundation/AliasLoader.php</h3>
<pre><code class="js">public function load($alias)
{
if (static::$facadeNamespace && strpos($alias, static::$facadeNamespace) === 0) {
$this->loadFacade($alias);
return true;
}
// $alias来自于config/app.php中aliases数组
if (isset($this->aliases[$alias])) {
//'Route' => Illuminate\Support\Facades\Route::class,
// class_alias 为一个类创建别名
return class_alias($this->aliases[$alias], $alias);
}
}</code></pre>
<h3>Illuminate/Support/Facades/Cache.php</h3>
<pre><code class="js">class Cache extends Facade
{
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return 'cache';
}
}</code></pre>
<h3>Illuminate/Support/Facades/Facade.php</h3>
<p>这个文件没有get set ,只有__callStatic</p>
<pre><code class="js">public static function __callStatic($method, $args)
{
$instance = static::getFacadeRoot();
if (! $instance) {
throw new RuntimeException('A facade root has not been set.');
}
return $instance->$method(...$args);
}
public static function getFacadeRoot()
{
return static::resolveFacadeInstance(static::getFacadeAccessor());
}
protected static function resolveFacadeInstance($name)
{
//这里$name为cache
if (is_object($name)) {
return $name;
}
if (isset(static::$resolvedInstance[$name])) {
return static::$resolvedInstance[$name];
}
//$app是容器对象,实现了ArrayAccess接口,最终调用的还是容器的make方法
return static::$resolvedInstance[$name] = static::$app[$name];
}</code></pre>
<h3>IlluminateContainerContainer.php</h3>
<pre><code class="js">public function make($abstract, array $parameters = [])
{
return $this->resolve($abstract, $parameters);
}
protected function resolve($abstract, $parameters = [])
{
$abstract = $this->getAlias($abstract);
$needsContextualBuild = ! empty($parameters) || ! is_null(
$this->getContextualConcrete($abstract)
);
// If an instance of the type is currently being managed as a singleton we'll
// just return an existing instance instead of instantiating new instances
// so the developer can keep using the same objects instance every time.
if (isset($this->instances[$abstract]) && ! $needsContextualBuild) {
return $this->instances[$abstract];
}
$this->with[] = $parameters;
$concrete = $this->getConcrete($abstract);
// We're ready to instantiate an instance of the concrete type registered for
// the binding. This will instantiate the types, as well as resolve any of
// its "nested" dependencies recursively until all have gotten resolved.
if ($this->isBuildable($concrete, $abstract)) {
$object = $this->build($concrete);
} else {
$object = $this->make($concrete);
}
// If we defined any extenders for this type, we'll need to spin through them
// and apply them to the object being built. This allows for the extension
// of services, such as changing configuration or decorating the object.
foreach ($this->getExtenders($abstract) as $extender) {
$object = $extender($object, $this);
}
// If the requested type is registered as a singleton we'll want to cache off
// the instances in "memory" so we can return it later without creating an
// entirely new instance of an object on each subsequent request for it.
if ($this->isShared($abstract) && ! $needsContextualBuild) {
$this->instances[$abstract] = $object;
}
$this->fireResolvingCallbacks($abstract, $object);
// Before returning, we will also set the resolved flag to "true" and pop off
// the parameter overrides for this build. After those two things are done
// we will be ready to return back the fully constructed class instance.
$this->resolved[$abstract] = true;
array_pop($this->with);
return $object;
}</code></pre>
<h3>Illuminate/Cache/CacheServiceProvider.php</h3>
<pre><code class="js"> public function register()
{
$this->app->singleton('cache', function ($app) {
return new CacheManager($app);
});
$this->app->singleton('cache.store', function ($app) {
return $app['cache']->driver();
});
$this->app->singleton('memcached.connector', function () {
return new MemcachedConnector;
});
}</code></pre>
<h3>get set</h3>
<pre><code class="js">$instance->$method(...$args)</code></pre>
<p><a href="https://link.segmentfault.com/?enc=KUYhWnzqAHAWlwWqia3tjA%3D%3D.Qsny4jycZa8cXNqrbMXOtbmQnBai5zAD17gA0%2B1pGnpLqvgXmT4ceCWeWcNvUWYy" rel="nofollow">laravel 中 Facades的原理以及代码剖析</a></p>
hexo 搭建博客
https://segmentfault.com/a/1190000017122993
2018-11-23T20:00:00+08:00
2018-11-23T20:00:00+08:00
苏生不惑
https://segmentfault.com/u/sushengbuhuo
7
<p>通常我们可以使用github pages 来搭建静态博客,建立一个username.github.io的项目就可以了,如果要将其他项目也作为页面展示,可以将代码推送到gh-pages分支。</p>
<p>GitHub pages木有默认样式,所以如果你不会自己写css,博客很难看的,所以我们需要hexo.</p>
<h3>准备</h3>
<p>先安装好git node hexo</p>
<h4>初始化</h4>
<pre><code class="javascript">$ hexo init blog
INFO Cloning hexo-starter to D:\code\hexo\blog
Cloning into 'D:\code\hexo\blog'...
remote: Enumerating objects: 68, done.
remote: Total 68 (delta 0), reused 0 (delta 0), pack-reused 68
Unpacking objects: 100% (68/68), done.
Submodule 'themes/landscape' (https://github.com/hexojs/hexo-theme-landscape.git) registered for path 'themes/landscape'
Cloning into 'D:/code/hexo/blog/themes/landscape'...
remote: Enumerating objects: 5, done.
remote: Counting objects: 100% (5/5), done.
remote: Compressing objects: 100% (5/5), done.
remote: Total 846 (delta 0), reused 1 (delta 0), pack-reused 841
Receiving objects: 100% (846/846), 2.55 MiB | 16.00 KiB/s, done.
Resolving deltas: 100% (445/445), done.
Submodule path 'themes/landscape': checked out '73a23c51f8487cfcd7c6deec96ccc7543960d350'
INFO Install dependencies
yarn install v1.9.4
info No lockfile found.
[1/4] Resolving packages...
warning hexo > titlecase@1.1.2: no longer maintained
warning hexo > nunjucks > postinstall-build@5.0.3: postinstall-build's behavior is now built into npm! You should migrate off of postinstall-build and use the new `prepare` lifecycle script with npm 5.0.0 or greater.
[2/4] Fetching packages...
info fsevents@1.2.4: The platform "win32" is incompatible with this module.
info "fsevents@1.2.4" is an optional dependency and failed compatibility check. Excluding it from installation.
[3/4] Linking dependencies...
[4/4] Building fresh packages...
success Saved lockfile.
Done in 18.06s.
INFO Start blogging with Hexo!
$ cd blog
$ npm install
npm WARN deprecated titlecase@1.1.2: no longer maintained
npm WARN deprecated postinstall-build@5.0.3: postinstall-build's behavior is now built into npm! You should migrate off of postinstall-build and use the new `prepare` lifecycle script with npm 5.0.0 or greater.
> nunjucks@3.1.4 postinstall D:\code\hexo\blog\node_modules\nunjucks
> node postinstall-build.js src
npm WARN rollback Rolling back node-pre-gyp@0.10.0 failed (this is probably harmless): EPERM: operation not permitted, rmdir 'D:\code\hexo\blog\node_modules\fsevents\node_modules'
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.4 (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.4: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
added 101 packages, removed 40 packages and updated 321 packages in 23.882s
$ ls
_config.yml package.json scaffolds/ themes/
node_modules/ package-lock.json source/ yarn.lock
$ hexo g
INFO Start processing
INFO Files loaded in 655 ms
INFO Generated: index.html
INFO Generated: archives/index.html
INFO Generated: fancybox/jquery.fancybox.css
INFO Generated: fancybox/blank.gif
INFO Generated: fancybox/fancybox_loading@2x.gif
INFO Generated: fancybox/fancybox_sprite@2x.png
INFO Generated: fancybox/jquery.fancybox.js
INFO Generated: fancybox/jquery.fancybox.pack.js
INFO Generated: fancybox/fancybox_sprite.png
INFO Generated: fancybox/fancybox_overlay.png
INFO Generated: archives/2018/11/index.html
INFO Generated: fancybox/fancybox_loading.gif
INFO Generated: css/fonts/FontAwesome.otf
INFO Generated: fancybox/helpers/jquery.fancybox-thumbs.css
INFO Generated: js/script.js
INFO Generated: fancybox/helpers/jquery.fancybox-buttons.js
INFO Generated: fancybox/helpers/jquery.fancybox-media.js
INFO Generated: fancybox/helpers/jquery.fancybox-buttons.css
INFO Generated: css/fonts/fontawesome-webfont.eot
INFO Generated: css/fonts/fontawesome-webfont.woff
INFO Generated: fancybox/helpers/fancybox_buttons.png
INFO Generated: fancybox/helpers/jquery.fancybox-thumbs.js
INFO Generated: css/style.css
INFO Generated: css/fonts/fontawesome-webfont.ttf
INFO Generated: archives/2018/index.html
INFO Generated: css/images/banner.jpg
INFO Generated: css/fonts/fontawesome-webfont.svg
INFO Generated: 2018/11/20/hello-world/index.html
INFO 28 files generated in 1.26 s
$ hexo s
INFO Start processing
INFO Hexo is running at http://localhost:4000 . Press Ctrl+C to stop
$ hexo d
ERROR Deployer not found: git
</code></pre>
<h3>GitHub key 配置</h3>
<pre><code class="javascript">1.生成指定名字的密钥
ssh-keygen -t rsa -C "xx@sina.com" -f ~/.ssh/github_sushengbuhuo
会生成 github_sushengbuhuo 和 github_sushengbuhuo.pub 这两个文件
2.密钥复制到托管平台上
vim ~/.ssh/github_sushengbuhuo.pub ,把内容复制至代码托管平台上
3.修改config文件 vim ~/.ssh/config #修改config文件,如果没有创建 config
Host sushengbuhuo.github.com
HostName github.com
User git
IdentityFile ~/.ssh/github_sushengbuhuo
Host abc.github.com
HostName github.com
User git
IdentityFile ~/.ssh/github_abc
4.测试验证
$ ssh -T git@github.com:
ssh: Could not resolve hostname github.com:: Name or service not known
$ ssh -T git@github.com
git@github.com: Permission denied (publickey).
$ ssh -T git@sushengbuhuo.github.com
Hi sushengbuhuo! You've successfully authenticated, but GitHub does not provide shell access.</code></pre>
<h4>配置config.yml</h4>
<pre><code class="javascript">deploy:
type: git
repository: git@sushengbuhuo.github.com:sushengbuhuo/sushengbuhuo.github.io.git
branch: master
theme: next</code></pre>
<h3>推送到GitHub</h3>
<pre><code class="javascript">$ hexo clean && hexo g
INFO Deleted database.
INFO Deleted public folder.
INFO Start processing
INFO Files loaded in 545 ms
INFO Generated: index.html
INFO Generated: archives/index.html
INFO Generated: fancybox/fancybox_loading.gif
INFO Generated: fancybox/fancybox_sprite@2x.png
INFO Generated: fancybox/jquery.fancybox.js
INFO Generated: fancybox/fancybox_overlay.png
INFO Generated: fancybox/jquery.fancybox.css
INFO Generated: fancybox/jquery.fancybox.pack.js
INFO Generated: fancybox/blank.gif
INFO Generated: fancybox/fancybox_loading@2x.gif
INFO Generated: fancybox/fancybox_sprite.png
INFO Generated: css/fonts/FontAwesome.otf
INFO Generated: archives/2018/11/index.html
INFO Generated: css/fonts/fontawesome-webfont.eot
INFO Generated: archives/2018/index.html
INFO Generated: fancybox/helpers/fancybox_buttons.png
INFO Generated: fancybox/helpers/jquery.fancybox-thumbs.js
INFO Generated: css/fonts/fontawesome-webfont.woff
INFO Generated: fancybox/helpers/jquery.fancybox-buttons.css
INFO Generated: js/script.js
INFO Generated: fancybox/helpers/jquery.fancybox-buttons.js
INFO Generated: css/style.css
INFO Generated: fancybox/helpers/jquery.fancybox-thumbs.css
INFO Generated: 2018/11/20/hello-world/index.html
INFO Generated: css/fonts/fontawesome-webfont.ttf
INFO Generated: css/fonts/fontawesome-webfont.svg
INFO Generated: css/images/banner.jpg
INFO Generated: fancybox/helpers/jquery.fancybox-media.js
INFO 28 files generated in 1.13 s
$ hexo d
ERROR Deployer not found: git
$ npm install hexo-deployer-git --save
npm WARN deprecated swig@1.4.2: This package is no longer maintained
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.4 (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.4: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
+ hexo-deployer-git@0.3.1
added 31 packages in 17.866s
$ hexo d
INFO Deploying: git
INFO Setting up Git deployment...
Initialized empty Git repository in D:/code/hexo/blog/.deploy_git/.git/
[master (root-commit) 9c86786] First commit
Committer: unknown <xxx@sina.com.cn>
Your name and email address were configured automatically based
on your username and hostname. Please check that they are accurate.
You can suppress this message by setting them explicitly:
git config --global user.name "Your Name"
git config --global user.email you@example.com
After doing this, you may fix the identity used for this commit with:
git commit --amend --reset-author
1 file changed, 0 insertions(+), 0 deletions(-)
create mode 100644 placeholder
INFO Clearing .deploy_git folder...
INFO Copying files from public folder...
INFO Copying files from extend dirs...
warning: LF will be replaced by CRLF in 2018/11/20/hello-world/index.html.
The file will have its original line endings in your working directory.
warning: LF will be replaced by CRLF in archives/2018/11/index.html.
The file will have its original line endings in your working directory.
warning: LF will be replaced by CRLF in archives/2018/index.html.
The file will have its original line endings in your working directory.
warning: LF will be replaced by CRLF in archives/index.html.
The file will have its original line endings in your working directory.
warning: LF will be replaced by CRLF in css/style.css.
The file will have its original line endings in your working directory.
warning: LF will be replaced by CRLF in fancybox/helpers/jquery.fancybox-buttons.css.
The file will have its original line endings in your working directory.
warning: LF will be replaced by CRLF in fancybox/helpers/jquery.fancybox-buttons.js.
The file will have its original line endings in your working directory.
warning: LF will be replaced by CRLF in fancybox/helpers/jquery.fancybox-media.js.
The file will have its original line endings in your working directory.
warning: LF will be replaced by CRLF in fancybox/helpers/jquery.fancybox-thumbs.css.
The file will have its original line endings in your working directory.
warning: LF will be replaced by CRLF in fancybox/helpers/jquery.fancybox-thumbs.js.
The file will have its original line endings in your working directory.
warning: LF will be replaced by CRLF in fancybox/jquery.fancybox.css.
The file will have its original line endings in your working directory.
warning: LF will be replaced by CRLF in fancybox/jquery.fancybox.js.
The file will have its original line endings in your working directory.
warning: LF will be replaced by CRLF in fancybox/jquery.fancybox.pack.js.
The file will have its original line endings in your working directory.
warning: LF will be replaced by CRLF in index.html.
The file will have its original line endings in your working directory.
warning: LF will be replaced by CRLF in js/script.js.
The file will have its original line endings in your working directory.
[master b7f7580] Site updated: 2018-11-20 11:51:50
Committer: unknown <xxx@sina.com.cn>
Your name and email address were configured automatically based
on your username and hostname. Please check that they are accurate.
You can suppress this message by setting them explicitly:
git config --global user.name "Your Name"
git config --global user.email you@example.com
After doing this, you may fix the identity used for this commit with:
git commit --amend --reset-author
29 files changed, 5777 insertions(+)
create mode 100644 2018/11/20/hello-world/index.html
create mode 100644 archives/2018/11/index.html
create mode 100644 archives/2018/index.html
create mode 100644 archives/index.html
create mode 100644 css/fonts/FontAwesome.otf
create mode 100644 css/fonts/fontawesome-webfont.eot
create mode 100644 css/fonts/fontawesome-webfont.svg
create mode 100644 css/fonts/fontawesome-webfont.ttf
create mode 100644 css/fonts/fontawesome-webfont.woff
create mode 100644 css/images/banner.jpg
create mode 100644 css/style.css
create mode 100644 fancybox/blank.gif
create mode 100644 fancybox/fancybox_loading.gif
create mode 100644 fancybox/fancybox_loading@2x.gif
create mode 100644 fancybox/fancybox_overlay.png
create mode 100644 fancybox/fancybox_sprite.png
create mode 100644 fancybox/fancybox_sprite@2x.png
create mode 100644 fancybox/helpers/fancybox_buttons.png
create mode 100644 fancybox/helpers/jquery.fancybox-buttons.css
create mode 100644 fancybox/helpers/jquery.fancybox-buttons.js
create mode 100644 fancybox/helpers/jquery.fancybox-media.js
create mode 100644 fancybox/helpers/jquery.fancybox-thumbs.css
create mode 100644 fancybox/helpers/jquery.fancybox-thumbs.js
create mode 100644 fancybox/jquery.fancybox.css
create mode 100644 fancybox/jquery.fancybox.js
create mode 100644 fancybox/jquery.fancybox.pack.js
create mode 100644 index.html
create mode 100644 js/script.js
delete mode 100644 placeholder
git@github.com: Permission denied (publickey).
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
FATAL Something's wrong. Maybe you can find the solution here: http://hexo.io/docs/troubleshooting.html
Error: git@github.com: Permission denied (publickey).
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
at ChildProcess.<anonymous> (D:\code\hexo\blog\node_modules\hexo-util\lib\spawn.js:37:17)
at emitTwo (events.js:126:13)
at ChildProcess.emit (events.js:214:7)
at ChildProcess.cp.emit (D:\code\hexo\blog\node_modules\cross-spawn\lib\enoent.js:40:29)
at maybeClose (internal/child_process.js:925:16)
at Socket.stream.socket.on (internal/child_process.js:346:11)
at emitOne (events.js:116:13)
at Socket.emit (events.js:211:7)
at Pipe._handle.close [as _onclose] (net.js:557:12)
$ hexo d
INFO Deploying: git
INFO Clearing .deploy_git folder...
INFO Copying files from public folder...
INFO Copying files from extend dirs...
warning: LF will be replaced by CRLF in 2018/11/20/hello-world/index.html.
The file will have its original line endings in your working directory.
warning: LF will be replaced by CRLF in archives/2018/11/index.html.
The file will have its original line endings in your working directory.
warning: LF will be replaced by CRLF in archives/2018/index.html.
The file will have its original line endings in your working directory.
warning: LF will be replaced by CRLF in archives/index.html.
The file will have its original line endings in your working directory.
warning: LF will be replaced by CRLF in css/style.css.
The file will have its original line endings in your working directory.
warning: LF will be replaced by CRLF in fancybox/helpers/jquery.fancybox-buttons.css.
The file will have its original line endings in your working directory.
warning: LF will be replaced by CRLF in fancybox/helpers/jquery.fancybox-buttons.js.
The file will have its original line endings in your working directory.
warning: LF will be replaced by CRLF in fancybox/helpers/jquery.fancybox-media.js.
The file will have its original line endings in your working directory.
warning: LF will be replaced by CRLF in fancybox/helpers/jquery.fancybox-thumbs.css.
The file will have its original line endings in your working directory.
warning: LF will be replaced by CRLF in fancybox/helpers/jquery.fancybox-thumbs.js.
The file will have its original line endings in your working directory.
warning: LF will be replaced by CRLF in fancybox/jquery.fancybox.css.
The file will have its original line endings in your working directory.
warning: LF will be replaced by CRLF in fancybox/jquery.fancybox.js.
The file will have its original line endings in your working directory.
warning: LF will be replaced by CRLF in fancybox/jquery.fancybox.pack.js.
The file will have its original line endings in your working directory.
warning: LF will be replaced by CRLF in js/script.js.
The file will have its original line endings in your working directory.
On branch master
nothing to commit, working tree clean
Branch 'master' set up to track remote branch 'master' from 'git@sushengbuhuo.github.com:sushengbuhuo/sushengbuhuo.github.io.git'.
To sushengbuhuo.github.com:sushengbuhuo/sushengbuhuo.github.io.git
+ 3037877...b7f7580 HEAD -> master (forced update)
INFO Deploy done: git
$ git clone https://github.com/iissnan/hexo-theme-next themes/next
Cloning into 'themes/next'...
remote: Enumerating objects: 12033, done.
remote: Total 12033 (delta 0), reused 0 (delta 0), pack-reused 12033
Receiving objects: 100% (12033/12033), 12.95 MiB | 79.00 KiB/s, done.
Resolving deltas: 100% (6966/6966), done.
$ hexo clean && hexo g
INFO Deleted database.
INFO Deleted public folder.
INFO Start processing
$ hexo d
$ hexo s
INFO Start processing
WARN ===============================================================
WARN ========================= ATTENTION! ==========================
WARN ===============================================================
WARN NexT repository is moving here: https://github.com/theme-next
WARN ===============================================================
WARN It's rebase to v6.0.0 and future maintenance will resume there
WARN ===============================================================
INFO Hexo is running at http://localhost:4000 . Press Ctrl+C to stop</code></pre>
<h3>安装插件</h3>
<p>登录<a href="https://link.segmentfault.com/?enc=2LAOT0w3iBeMjR46a3BtJQ%3D%3D.z%2FPZD0l%2FLvdjSX8g43SumPqHCahWnjBQYAV3Xlnh9Ts%3D" rel="nofollow">admin</a> 即可看到我们所有的文章内容</p>
<pre><code class="javascript">λ npm i hexo-admin --save
npm WARN deprecated minimatch@2.0.10: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue
npm WARN deprecated connect@2.7.11: connect 2.x series is deprecated
npm WARN deprecated cryptiles@2.0.5: This version is no longer maintained. Please upgrade to the latest version.
npm WARN deprecated boom@2.10.1: This version is no longer maintained. Please upgrade to the latest version.
npm WARN deprecated hoek@2.16.3: This version is no longer maintained. Please upgrade to the latest version.
npm WARN acorn-dynamic-import@4.0.0 requires a peer of acorn@^6.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.4 (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.4: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
+ hexo-admin@2.3.0
added 251 packages in 23.975s
╭─────────────────────────────────────╮
│ │
│ Update available 5.6.0 → 6.4.1 │
│ Run npm i npm to update │
│ │
╰─────────────────────────────────────╯
#网站底部字数统计
d:\code\hexo\blog
λ npm install hexo-wordcount --save
npm WARN rollback Rolling back node-pre-gyp@0.10.0 failed (this is probably harmless): EPERM: operation not permitted, scandir 'd:\code\hexo\blog\node_modules\fsevents\node_modules'
npm WARN acorn-dynamic-import@4.0.0 requires a peer of acorn@^6.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.4 (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.4: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
+ hexo-wordcount@6.0.1
added 1 package in 10.289s</code></pre>
<h3>中文乱码问题</h3>
<p>将config.yml 和md文件编码转为utf-8</p>
<p>修改config.yml <code>language: zh-Hans</code></p>
<h3>新建文章</h3>
<pre><code class="bash">$ hexo new "PHP依赖注入"</code></pre>
<p>Hexo 默认以标题为文件名称,可编辑_config.yml <code>new_post_name</code> 参数来改变默认的文件名称,设为 :year-:month-:day-:title.md 可更方便的通过日期来管理文章。</p>
<p><a href="https://link.segmentfault.com/?enc=Y%2FjeV0Q8%2Bcq5SemBMH96MQ%3D%3D.HIeMNOzilMD3NCcLI6uoXY4og4jyKxfIUTEPv%2B2WVh71XEjaXq0JVQmRACukBVxH" rel="nofollow">新写文章文档</a></p>
<h3>结尾</h3>
<p><a href="https://link.segmentfault.com/?enc=kT6j59tHqxlhy7QOUe%2B20Q%3D%3D.WRpncijTB8mj5APAj08tGgE75WEav3nSiMGGZQ2%2FWuY%3D" rel="nofollow">查看效果</a></p>
<h3>资源</h3>
<p><a href="https://link.segmentfault.com/?enc=p9O8C%2BpzHVEvVZ0Yau4HHQ%3D%3D.C8LMvn7bTv%2BmMFa159a5mTN9PzqieyKFiMaAsp3mbQg%3D" rel="nofollow">hexo文档</a></p>
<p><a href="https://link.segmentfault.com/?enc=B1PU1r3%2Bkx9oQDwABb82kw%3D%3D.r1sNU2k5TTk1cxQn8PGNHLZZBFAfyk7s5ZyqN6dWJu0rKQP5MLsPb4A%2F8q1RHJ3x" rel="nofollow">hexo问题交流</a> </p>
<p><a href="https://link.segmentfault.com/?enc=dWh%2FwjfBCUT6iitG%2BQ2XoA%3D%3D.1wyDSBTjCyQkqsbr3rxVC5Za%2FB%2F0%2BZtBXwmkOR1PcNtCeRtRPSygTtaUcpG8%2Fcjm" rel="nofollow">Deployment</a></p>
<p><a href="https://link.segmentfault.com/?enc=2XUJM0A%2B5P7EkdOJNGWWog%3D%3D.YdIXXz2%2FUa4cIKbbMz2YbfsR4NdGtwZizExcxeDk6bknAjzE%2BQmw0u%2B5kSvyW0yT" rel="nofollow">绝配:hexo+next主题及我走过的坑</a></p>
<p><a href="https://link.segmentfault.com/?enc=i9m8rvbSZwYqEqXJsPOXlA%3D%3D.VwJ4YQCPRZkaVNhctNnOj%2BVYhBBiYXeg6fUOsfI1FM07DoC9jk1txu8RrUEbxtSmakuYj3EuLkHSRQ4rZf%2Fj4w%3D%3D" rel="nofollow">Hexo+Pages静态博客-Next主题篇</a></p>
<p><a href="https://link.segmentfault.com/?enc=8UJ31fQWnEr95Kh5qAWZPw%3D%3D.05Bh9iQjMRlD0%2BYi2kzbxlCNfba6CjQhYmsuU5rfDGUD6cWzXv3%2F3H2sPp%2BgKYWt%2BSE09rWNRYwnJ%2FDVj9hkrg%3D%3D" rel="nofollow">关于HEXO搭建个人博客的点点滴滴</a></p>
<p><a href="https://link.segmentfault.com/?enc=eQr4r69rcBUwoV3L0KWrZw%3D%3D.Q%2F2urCZsR7Pn3DMGedmcCEz%2BUx3aAq7GHoWeHAlBO9603fjfrYDdiyY2VGGw8YV%2FhjQ3z3uqhQVwTXbXtOzX%2FHBrRXlZg0Uw13QZXvDwD35Z2IjodIL4EwcDtY%2Ffbz1G6zzOqvtmZJ%2BpJUPNwThAVw%3D%3D" rel="nofollow">搭建博客</a></p>
<p><a href="https://link.segmentfault.com/?enc=SJj93OEjGsIYTM%2BAQd16dA%3D%3D.mqUdzoVRDrX9sKFfExuWzWtAyXpYbDsy4uFmPv51lJ8Ek3Y%2Fj4kv%2BqbzOeO2k7zA" rel="nofollow">手把手教你用Hexo搭建个人技术博客</a></p>
<p><a href="https://segmentfault.com/a/1190000012907499">基于CentOS搭建Hexo博客</a></p>
<p><a href="https://link.segmentfault.com/?enc=Y5Pj6bhn8xHfd8mZPO8B2A%3D%3D.y1g8AdS7akPRcGz6wC%2FXNQ9QZtgIpyt9EAiik7EnlqoUYY6DgcSi0LITjHvMy8Bq" rel="nofollow">最快的 Hexo 博客搭建方法</a></p>
<p><a href="https://link.segmentfault.com/?enc=dtSJRmj%2FZb2s5TqDTTcirQ%3D%3D.yZPNPaZJ6ibFOBg9OQdlHxo7deBMLCQlp3W1xD9wR3NUz3g3DZqXQstqXxx35iqM" rel="nofollow">超详细Hexo+Github博客搭建小白教程</a></p>
<p><a href="https://link.segmentfault.com/?enc=cIqt%2BoPWN3I42JfI3K6nBg%3D%3D.hwN08A2q8Awvhab3c8x2gY359om7NDEr%2BSLqnrYzwxGarmp9TYH%2FndwjVmeW3%2FKCv93i5Niot8lyyqo4yV61IA%3D%3D" rel="nofollow">在Github上备份Hexo博客</a></p>
<p><a href="https://link.segmentfault.com/?enc=%2BVYRn%2BIibmJOAUM0NTU9qg%3D%3D.WsyXbDBa%2BKSDhIvzsU6UAnMYuz54blEHRY6F6%2FkK6TrbB05EfBWuz4ZtBt9%2F5Vf8" rel="nofollow">最快的 Hexo 博客搭建方法</a></p>
开源的数据探查与可视化平台superset
https://segmentfault.com/a/1190000016892955
2018-11-03T10:11:15+08:00
2018-11-03T10:11:15+08:00
苏生不惑
https://segmentfault.com/u/sushengbuhuo
2
<h3>安装 pip superset</h3>
<pre><code class="js">curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
python get-pip.py
λ pip install superset
Collecting superset
Downloading https://files.pythonhosted.org/packages/80/98/8ffd47f4b68b11d00e0cad5a3a61b4e28a56bd79c47623c8c31e04faa8cb/superset-0.28.0.tar.gz (52.7MB)
100% |████████████████████████████████| 52.7MB 88kB/s
Requirement already satisfied: bleach in d:\python\lib\site-packages (from superset) (2.1.4)
Requirement already satisfied: boto3==1.4.7 in d:\python\lib\site-packages (from superset) (1.4.7)
Requirement already satisfied: botocore<1.8.0,>=1.7.0 in d:\python\lib\site-packages (from superset) (1.7.48)
Requirement already satisfied: celery>=4.2.0 in d:\python\lib\site-packages (from superset) (4.2.1)
Requirement already satisfied: click==6.7 in d:\python\lib\site-packages (from superset) (6.7)
Requirement already satisfied: colorama==0.3.9 in d:\python\lib\site-packages (from superset) (0.3.9)
Requirement already satisfied: contextlib2 in d:\python\lib\site-packages (from superset) (0.5.5)
Requirement already satisfied: cryptography in d:\python\lib\site-packages (from superset) (2.3.1)
Requirement already satisfied: flask<1.0.0 in d:\python\lib\site-packages (from superset) (0.12.4)
Collecting flask-appbuilder>=1.12.0 (from superset)
Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProtocolError('Connection aborted.', ConnectionResetError(10054, '远程主机强迫
关闭了一个现有的连接。', None, 10054, None))': /simple/flask-appbuilder/
Downloading https://files.pythonhosted.org/packages/ca/7b/a4c899095e1ca0eb732cca22934ce483b78b05329f37b97ae0e6e0e3f386/Flask-AppBuilder-1.12.1.tar.gz (2.3MB)
100% |████████████████████████████████| 2.3MB 63kB/s
Requirement already satisfied: flask-caching in d:\python\lib\site-packages (from superset) (1.4.0)
Requirement already satisfied: flask-compress in d:\python\lib\site-packages (from superset) (1.4.0)
Requirement already satisfied: flask-migrate in d:\python\lib\site-packages (from superset) (2.2.1)
Requirement already satisfied: flask-wtf in d:\python\lib\site-packages (from superset) (0.14.2)
Requirement already satisfied: flower in d:\python\lib\site-packages (from superset) (0.9.2)
Requirement already satisfied: future<0.17,>=0.16.0 in d:\python\lib\site-packages (from superset) (0.16.0)
Requirement already satisfied: geopy in d:\python\lib\site-packages (from superset) (1.16.0)
Requirement already satisfied: gunicorn in d:\python\lib\site-packages (from superset) (19.9.0)
Requirement already satisfied: humanize in d:\python\lib\site-packages (from superset) (0.5.1)
Requirement already satisfied: idna in d:\python\lib\site-packages (from superset) (2.7)
Requirement already satisfied: isodate in d:\python\lib\site-packages (from superset) (0.6.0) Collecting markdown>=3.0 (from superset)
Downloading https://files.pythonhosted.org/packages/7a/6b/5600647404ba15545ec37d2f7f58844d690baf2f81f3a60b862e48f29287/Markdown-3.0.1-py2.py3-none-any.whl (89kB)
100% |████████████████████████████████| 92kB 38kB/s
Requirement already satisfied: pandas>=0.18.0 in d:\python\lib\site-packages (from superset) (0.23.4)
Requirement already satisfied: parsedatetime in d:\python\lib\site-packages (from superset) (2.4)
Requirement already satisfied: pathlib2 in d:\python\lib\site-packages (from superset) (2.3.2)
Requirement already satisfied: polyline in d:\python\lib\site-packages (from superset) (1.3.2)
Requirement already satisfied: pydruid>=0.4.3 in d:\python\lib\site-packages (from superset) (0.4.5)
Requirement already satisfied: pyhive>=0.4.0 in d:\python\lib\site-packages (from superset) (0.6.0)
Requirement already satisfied: python-dateutil in d:\python\lib\site-packages (from superset) (2.7.3)
Requirement already satisfied: python-geohash in d:\python\lib\site-packages (from superset) (0.8.5)
Requirement already satisfied: pyyaml>=3.11 in d:\python\lib\site-packages (from superset) (3.13)
Requirement already satisfied: requests in d:\python\lib\site-packages (from superset) (2.19.1)
Requirement already satisfied: simplejson>=3.15.0 in d:\python\lib\site-packages (from superset) (3.16.0)
Requirement already satisfied: sqlalchemy in d:\python\lib\site-packages (from superset) (1.2.11)
Requirement already satisfied: sqlalchemy-utils in d:\python\lib\site-packages (from superset) (0.33.3)
Requirement already satisfied: sqlparse in d:\python\lib\site-packages (from superset) (0.2.4)
Collecting tableschema (from superset)
Downloading https://files.pythonhosted.org/packages/28/29/2fd3744510a745bee4735bd34cb44f9a0cc02e646d929a40aa5b2f8b85d8/tableschema-1.2.5-py2.py3-none-any.whl (55kB)
100% |████████████████████████████████| 61kB 77kB/s
Requirement already satisfied: thrift>=0.9.3 in d:\python\lib\site-packages (from superset) (0.11.0)
Requirement already satisfied: thrift-sasl>=0.2.1 in d:\python\lib\site-packages (from superset) (0.3.0)
Requirement already satisfied: unicodecsv in d:\python\lib\site-packages (from superset) (0.14.1)
Requirement already satisfied: unidecode>=0.04.21 in d:\python\lib\site-packages (from superset) (1.0.22)
Requirement already satisfied: html5lib!=1.0b1,!=1.0b2,!=1.0b3,!=1.0b4,!=1.0b5,!=1.0b6,!=1.0b7,!=1.0b8,>=0.99999999pre in d:\python\lib\site-packages (from bleach->superset) (1.0.1)
Requirement already satisfied: six in d:\python\lib\site-packages (from bleach->superset) (1.11.0)
Requirement already satisfied: jmespath<1.0.0,>=0.7.1 in d:\python\lib\site-packages (from boto3==1.4.7->superset) (0.9.3)
Requirement already satisfied: s3transfer<0.2.0,>=0.1.10 in d:\python\lib\site-packages (from boto3==1.4.7->superset) (0.1.13)
Requirement already satisfied: docutils>=0.10 in d:\python\lib\site-packages (from botocore<1.8.0,>=1.7.0->superset) (0.14)
Requirement already satisfied: pytz>dev in d:\python\lib\site-packages (from celery>=4.2.0->superset) (2018.5)
Requirement already satisfied: billiard<3.6.0,>=3.5.0.2 in d:\python\lib\site-packages (from celery>=4.2.0->superset) (3.5.0.4)
Requirement already satisfied: kombu<5.0,>=4.2.0 in d:\python\lib\site-packages (from celery>=4.2.0->superset) (4.2.1)
Requirement already satisfied: asn1crypto>=0.21.0 in d:\python\lib\site-packages (from cryptography->superset) (0.24.0)
Requirement already satisfied: cffi!=1.11.3,>=1.7 in d:\python\lib\site-packages (from cryptography->superset) (1.11.5)
Requirement already satisfied: Jinja2>=2.4 in d:\python\lib\site-packages (from flask<1.0.0->superset) (2.10)
Requirement already satisfied: itsdangerous>=0.21 in d:\python\lib\site-packages (from flask<1.0.0->superset) (0.24)
Requirement already satisfied: Werkzeug>=0.7 in d:\python\lib\site-packages (from flask<1.0.0->superset) (0.14.1)
Requirement already satisfied: Flask-Babel<1,>=0.11.1 in d:\python\lib\site-packages (from flask-appbuilder>=1.12.0->superset) (0.11.1)
Collecting Flask-Login<0.5,>=0.3 (from flask-appbuilder>=1.12.0->superset)
Downloading https://files.pythonhosted.org/packages/c1/ff/bd9a4d2d81bf0c07d9e53e8cd3d675c56553719bbefd372df69bf1b3c1e4/Flask-Login-0.4.1.tar.gz
Requirement already satisfied: Flask-OpenID<2,>=1.2.5 in d:\python\lib\site-packages (from flask-appbuilder>=1.12.0->superset) (1.2.5)
Collecting Flask-SQLAlchemy<3,>=2.3 (from flask-appbuilder>=1.12.0->superset)
Downloading https://files.pythonhosted.org/packages/a1/44/294fb7f6bf49cc7224417cd0637018db9fee0729b4fe166e43e2bbb1f1c8/Flask_SQLAlchemy-2.3.2-py2.py3-none-any.whl
Requirement already satisfied: alembic>=0.7 in d:\python\lib\site-packages (from flask-migrate->superset) (1.0.0)
Requirement already satisfied: WTForms in d:\python\lib\site-packages (from flask-wtf->superset) (2.2.1)
Requirement already satisfied: tornado>=4.2.0 in d:\python\lib\site-packages (from flower->superset) (5.1)
Requirement already satisfied: babel>=1.0 in d:\python\lib\site-packages (from flower->superset) (2.6.0)
Requirement already satisfied: geographiclib<2,>=1.49 in d:\python\lib\site-packages (from geopy->superset) (1.49)
Requirement already satisfied: numpy>=1.9.0 in d:\python\lib\site-packages (from pandas>=0.18.0->superset) (1.15.1)
Requirement already satisfied: certifi>=2017.4.17 in d:\python\lib\site-packages (from requests->superset) (2018.8.24)
Requirement already satisfied: chardet<3.1.0,>=3.0.2 in d:\python\lib\site-packages (from requests->superset) (3.0.4)
Requirement already satisfied: urllib3<1.24,>=1.21.1 in d:\python\lib\site-packages (from requests->superset) (1.23)
Requirement already satisfied: jsonschema<3.0,>=2.5 in d:\python\lib\site-packages (from tableschema->superset) (2.6.0)
Requirement already satisfied: rfc3986<2.0,>=1.1.0 in d:\python\lib\site-packages (from tableschema->superset) (1.1.0)
Collecting tabulator<2.0,>=1.3 (from tableschema->superset)
Downloading https://files.pythonhosted.org/packages/63/a6/33d0b08ce84fd1cdf0fb57e81bc822345007dd698cc5273b7ef916fce5ed/tabulator-1.17.0-py2.py3-none-any.whl (50kB)
100% |████████████████████████████████| 51kB 168kB/s
Requirement already satisfied: pure-sasl>=0.3.0 in d:\python\lib\site-packages (from thrift-sasl>=0.2.1->superset) (0.5.1)
Requirement already satisfied: webencodings in d:\python\lib\site-packages (from html5lib!=1.0b1,!=1.0b2,!=1.0b3,!=1.0b4,!=1.0b5,!=1.0b6,!=1.0b7,!=1.0b8,>=0.99999999pre->bleach->superset) (0.5.1)
Requirement already satisfied: amqp<3.0,>=2.1.4 in d:\python\lib\site-packages (from kombu<5.0,>=4.2.0->celery>=4.2.0->superset) (2.3.2)
Requirement already satisfied: pycparser in d:\python\lib\site-packages (from cffi!=1.11.3,>=1.7->cryptography->superset) (2.18)
Requirement already satisfied: MarkupSafe>=0.23 in d:\python\lib\site-packages (from Jinja2>=2.4->flask<1.0.0->superset) (1.0)
Requirement already satisfied: python3-openid>=2.0 in d:\python\lib\site-packages (from Flask-OpenID<2,>=1.2.5->flask-appbuilder>=1.12.0->superset) (3.1.0)
Requirement already satisfied: python-editor>=0.3 in d:\python\lib\site-packages (from alembic>=0.7->flask-migrate->superset) (1.0.3)
Requirement already satisfied: Mako in d:\python\lib\site-packages (from alembic>=0.7->flask-migrate->superset) (1.0.7)
Requirement already satisfied: xlrd<2.0,>=1.0 in d:\python\lib\site-packages (from tabulator<2.0,>=1.3->tableschema->superset) (1.1.0)
Requirement already satisfied: linear-tsv<2.0,>=1.0 in d:\python\lib\site-packages (from tabulator<2.0,>=1.3->tableschema->superset) (1.1.0)
Requirement already satisfied: jsonlines<2.0,>=1.1 in d:\python\lib\site-packages (from tabulator<2.0,>=1.3->tableschema->superset) (1.2.0)
Requirement already satisfied: openpyxl<2.5,>=2.4 in d:\python\lib\site-packages (from tabulator<2.0,>=1.3->tableschema->superset) (2.4.11)
Collecting cchardet<3.0,>=1.0 (from tabulator<2.0,>=1.3->tableschema->superset)
Downloading https://files.pythonhosted.org/packages/dd/6a/6b54a269caa3518b6eaab3aec0fa4fa9eaa8019b4ae84a7c3ef66b1f9be0/cchardet-2.1.4-cp37-cp37m-win32.whl (89kB)
100% |████████████████████████████████| 92kB 184kB/s
Requirement already satisfied: ijson<3.0,>=2.0 in d:\python\lib\site-packages (from tabulator<2.0,>=1.3->tableschema->superset) (2.3)
Requirement already satisfied: vine>=1.1.3 in d:\python\lib\site-packages (from amqp<3.0,>=2.1.4->kombu<5.0,>=4.2.0->celery>=4.2.0->superset) (1.1.4)
Requirement already satisfied: defusedxml in d:\python\lib\site-packages (from python3-openid>=2.0->Flask-OpenID<2,>=1.2.5->flask-appbuilder>=1.12.0->superset) (0.5.0)
Requirement already satisfied: jdcal in d:\python\lib\site-packages (from openpyxl<2.5,>=2.4->tabulator<2.0,>=1.3->tableschema->superset) (1.4)
Requirement already satisfied: et-xmlfile in d:\python\lib\site-packages (from openpyxl<2.5,>=2.4->tabulator<2.0,>=1.3->tableschema->superset) (1.0.1)
Installing collected packages: Flask-Login, Flask-SQLAlchemy, flask-appbuilder, markdown, cchardet, tabulator, tableschema, superset
Found existing installation: Flask-Login 0.2.11
Uninstalling Flask-Login-0.2.11:
Successfully uninstalled Flask-Login-0.2.11
Running setup.py install for Flask-Login ... done
Found existing installation: Flask-SQLAlchemy 2.1
Uninstalling Flask-SQLAlchemy-2.1:
Successfully uninstalled Flask-SQLAlchemy-2.1
Found existing installation: Flask-AppBuilder 1.10.0
Uninstalling Flask-AppBuilder-1.10.0:
Successfully uninstalled Flask-AppBuilder-1.10.0
Running setup.py install for flask-appbuilder ... done
Found existing installation: Markdown 2.6.11
Uninstalling Markdown-2.6.11:
Successfully uninstalled Markdown-2.6.11
Running setup.py install for superset ... done
Successfully installed Flask-Login-0.4.1 Flask-SQLAlchemy-2.3.2 cchardet-2.1.4 flask-appbuilder-1.12.1 markdown-3.0.1 superset-0.28.0 tableschema-1.2.5 tabulator-1.17.0
You are using pip version 18.0, however version 18.1 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.
# 创建管理员帐号
fabmanager create-admin --app superset
Username [admin]: xxx
User first name [admin]: xxx
User last name [user]: xxx
Email [admin@fab.org]: xxx@qq.cn
Password:
Repeat for confirmation:
Recognized Database Authentications.
Admin User xxx created.
# 初始化数据库 (windows下,先进入到
Python安装目录(或者virtualEnv的虚拟目录)下,lib\site-packages\superset\bin下)
cd /d/python/lib/site-packages/superset/bin
Python superset db upgrade
INFO [alembic.runtime.migration] Context impl SQLiteImpl.
INFO [alembic.runtime.migration] Will assume transactional DDL
# 加载例子(后续操作都需要在lib\site-packages\superset\bin下)
Python superset load_examples
2018-10-18 20:36:31,358:INFO:root:Creating database reference
2018-10-18 20:36:31,401:INFO:root:Database.get_sqla_engine(). Masked URL: sqlite:///C:\Users\xxx\.superset\superset.db
2018-10-18 20:36:42,164:INFO:root:Creating database reference
2018-10-18 20:36:44,521:INFO:root:Creating database reference
2018-10-18 20:36:45,654:INFO:root:Creating database reference
2018-10-18 20:37:02,201:INFO:root:Creating database reference
2018-10-18 20:37:02,378:INFO:root:Creating database reference
2018-10-18 20:37:02,547:INFO:root:Creating database reference
2018-10-18 20:37:04,243:INFO:root:Creating database reference
2018-10-18 20:37:04,380:INFO:root:Creating database reference
2018-10-18 20:37:08,631:INFO:root:Creating database reference
2018-10-18 20:37:08,789:INFO:root:Creating database reference
2018-10-18 20:37:19,065:INFO:root:Creating database reference
2018-10-18 20:37:21,217:INFO:root:Creating database reference
Loading examples into <SQLA engine=sqlite:///C:\Users\xxx\.superset\superset.db>
Creating default CSS templates
Loading energy related dataset
Creating table [wb_health_population] reference
Loading [World Bank's Health Nutrition and Population Stats]
Creating table [wb_health_population] reference
Creating slices
Creating a World's Health Bank dashboard
Loading [Birth names]
Done loading table!
--------------------------------------------------------------------------------
Creating table [birth_names] reference
Creating some slices
Creating a dashboard
Loading [Random time series data]
Done loading table!
--------------------------------------------------------------------------------
Creating table [random_time_series] reference
Creating a slice
Loading [Random long/lat data]
Done loading table!
--------------------------------------------------------------------------------
Creating table reference
Creating a slice
Loading [Country Map data]
Done loading table!
--------------------------------------------------------------------------------
Creating table reference
Creating a slice
Loading [Multiformat time series]
Done loading table!
--------------------------------------------------------------------------------
Creating table [multiformat_time_series] reference
Creating Heatmap charts
Loading [Paris GeoJson]
Creating table paris_iris_mapping reference
Loading [San Francisco population polygons]
Creating table sf_population_polygons reference
Loading [Flights data]
Done loading table!
Loading [BART lines]
Creating table bart_lines reference
Loading [Multi Line]
Creating table [wb_health_population] reference
Creating slices
Creating a World's Health Bank dashboard
Done loading table!
--------------------------------------------------------------------------------
Creating table [birth_names] reference
Creating some slices
Creating a dashboard
Loading [Misc Charts] dashboard
Creating the dashboard
Loading DECK.gl demo
Loading deck.gl dashboard
Creating Scatterplot slice
Creating Screen Grid slice
Creating Hex slice
Creating Grid slice
Creating Polygon slice
Creating Arc slice
Creating Path slice
Creating a dashboard
# 初始化角色和权限
Python superset init
2018-10-18 20:38:30,683:INFO:root:Creating database reference
2018-10-18 20:38:30,690:INFO:root:Syncing role definition
2018-10-18 20:38:30,697:INFO:root:Syncing Admin perms
2018-10-18 20:38:30,771:INFO:root:Syncing Alpha perms
2018-10-18 20:38:30,845:INFO:root:Syncing Gamma perms
2018-10-18 20:38:30,919:INFO:root:Syncing granter perms
2018-10-18 20:38:30,993:INFO:root:Syncing sql_lab perms
2018-10-18 20:38:31,072:INFO:root:Fetching a set of all perms to lookup which ones are missing
2018-10-18 20:38:31,174:INFO:root:Creating missing datasource permissions.
2018-10-18 20:38:31,182:INFO:root:Creating missing database permissions.
2018-10-18 20:38:31,184:INFO:root:Creating missing metrics permissions
2018-10-18 20:38:31,216:INFO:root:Cleaning faulty perms
$ python superset runserver
2018-10-18 20:38:48,839:INFO:root:The Gunicorn 'superset runserver' command is deprecated. Please use the 'gunicorn' command instead.
Traceback (most recent call last):
File "d:\python\lib\runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "d:\python\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "D:\python\Scripts\gunicorn.exe\__main__.py", line 5, in <module>
File "d:\python\lib\site-packages\gunicorn\app\wsgiapp.py", line 9, in <module>
from gunicorn.app.base import Application
File "d:\python\lib\site-packages\gunicorn\app\base.py", line 12, in <module>
from gunicorn import util
File "d:\python\lib\site-packages\gunicorn\util.py", line 9, in <module>
import fcntl
ModuleNotFoundError: No module named 'fcntl'
Starting server with command:
gunicorn -w 2 --timeout 60 -b 0.0.0.0:8088 --limit-request-line 0 --limit-request-field_size 0 superset:app
# 启动服务,端口 8088, 使用 -p 更改端口号。
Python superset runserver -d
2018-10-18 20:40:14,223:INFO:werkzeug: * Restarting with stat
2018-10-18 20:40:17,704:WARNING:werkzeug: * Debugger is active!
2018-10-18 20:40:17,720:INFO:werkzeug: * Debugger PIN: 139-127-258
2018-10-18 20:40:17,732:INFO:werkzeug: * Running on http://0.0.0.0:8088/ (Press CTRL+C to quit)</code></pre>
<h3>安装MySQL包</h3>
<pre><code class="js">λ pip install mysqlclient
Collecting mysqlclient
Using cached https://files.pythonhosted.org/packages/ec/fd/83329b9d3e14f7344d1cb31f128e6dbba70c5975c9e57896815dbb1988ad/mysqlclient-1.3.13.tar.gz
Installing collected packages: mysqlclient
Running setup.py install for mysqlclient ... error
Complete output from command d:\python\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\xxxx\\AppData\\Local\\Temp\\pip-install-wmrhs8m3\\mysqlclient\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\xxxx\AppData\Local\Temp\pip-record-z4r5l4fy\install-record.txt --single-version-externally-managed --compile:
d:\python\lib\distutils\dist.py:274: UserWarning: Unknown distribution option: 'long_description_content_type'
warnings.warn(msg)
running install
running build
running build_py
creating build
creating build\lib.win32-3.7
copying _mysql_exceptions.py -> build\lib.win32-3.7
creating build\lib.win32-3.7\MySQLdb
copying MySQLdb\__init__.py -> build\lib.win32-3.7\MySQLdb
copying MySQLdb\compat.py -> build\lib.win32-3.7\MySQLdb
copying MySQLdb\connections.py -> build\lib.win32-3.7\MySQLdb
copying MySQLdb\converters.py -> build\lib.win32-3.7\MySQLdb
copying MySQLdb\cursors.py -> build\lib.win32-3.7\MySQLdb
copying MySQLdb\release.py -> build\lib.win32-3.7\MySQLdb
copying MySQLdb\times.py -> build\lib.win32-3.7\MySQLdb
creating build\lib.win32-3.7\MySQLdb\constants
copying MySQLdb\constants\__init__.py -> build\lib.win32-3.7\MySQLdb\constants
copying MySQLdb\constants\CLIENT.py -> build\lib.win32-3.7\MySQLdb\constants
copying MySQLdb\constants\CR.py -> build\lib.win32-3.7\MySQLdb\constants
copying MySQLdb\constants\ER.py -> build\lib.win32-3.7\MySQLdb\constants
copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win32-3.7\MySQLdb\constants
copying MySQLdb\constants\FLAG.py -> build\lib.win32-3.7\MySQLdb\constants
copying MySQLdb\constants\REFRESH.py -> build\lib.win32-3.7\MySQLdb\constants
running build_ext
building '_mysql' extension
error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools
----------------------------------------
Command "d:\python\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\xxx\\AppData\\Local\\Temp\\pip-install-wmrhs8m3\\mysqlclient\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\xxx\AppData\Local\Temp\pip-record-z4r5l4fy\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\xxx\AppData\Local\Temp\pip-install-wmrhs8m3\mysqlclient\</code></pre>
<p><img src="/img/bVbiodT?w=1087&h=899" alt="clipboard.png" title="clipboard.png"></p>
<pre><code class="js">$ curl https://download.lfd.uci.edu/pythonlibs/h2ufg7oq/mysqlclient-1.3.13-cp37-cp37m-win32.whl -o mysqlclient-1.3.13-cp37-cp37m-win32.whl
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 1211k 100 1211k 0 0 2087 0 0:09:54 0:09:54 --:--:-- 26499
$ pip install mysqlclient-1.3.13-cp37-cp37m-win32.whl
Processing d:\code\mysqlclient-1.3.13-cp37-cp37m-win32.whl
Installing collected packages: mysqlclient
Successfully installed mysqlclient-1.3.13
</code></pre>
<h3>测试连接</h3>
<p><img src="/img/bVbin7c?w=1520&h=797" alt="clipboard.png" title="clipboard.png"></p>
<h3>参考</h3>
<p><a href="https://link.segmentfault.com/?enc=466w0avIeEnm6qzN%2BhoapA%3D%3D.1OvmswfXyzNcqD%2BiXFCesOe19h8lJGjrcciftl2Lmlc%3D" rel="nofollow">http://timd.cn/superset/</a><br><a href="https://link.segmentfault.com/?enc=kY2IS%2FQeusKgo%2FzuXRr71w%3D%3D.%2FGKH8bqkxSgAHFS%2FysHKIJaZUseDJwQznSWiKQLNjc5nXuVmOZ64uHap9WnEpk3r" rel="nofollow">https://www.v2ex.com/amp/t/43...</a> <br><a href="https://link.segmentfault.com/?enc=tAuPmOdACSofVdyVRQJ0XA%3D%3D.bkJGMI3le000RUk4KrIvMIeEdJpSD4Smk8wnFaat3GIuN9Iw2JYbzYfXdMW5vsAUyzVF3wboPy3XquBKv4EfkA%3D%3D" rel="nofollow">https://blog.csdn.net/qq_3344...</a> <br><a href="https://link.segmentfault.com/?enc=DqBTNJF6FzQdWlUUQ9sQYg%3D%3D.ziSTHo6n8Op%2BPv4aLgYFG3oh9FdymsHnfnnWymM%2B43%2BR074LkafUfPgFVqVztYU%2B" rel="nofollow">https://zhuanlan.zhihu.com/p/...</a> <br><a href="https://link.segmentfault.com/?enc=%2B9iriUtQKT%2BYBW0stwGXEQ%3D%3D.JIcHopzYzAUwgMblEMfHjfKTRX6E7%2FXN03Y7Wli9N9QSoqWxnPin4JMh%2FQzIpxUI" rel="nofollow">https://www.cnblogs.com/calmz...</a> <br><a href="https://link.segmentfault.com/?enc=q2%2Fra5SR8Y9lQpdw7ZNwNg%3D%3D.gP%2FAtHHRgGFtuAMzL2kcC9GfBMsaUyfb6F7cjVcV%2BI9ghg4DlmFLKGOOWDIovdeu" rel="nofollow">https://www.cnblogs.com/calmz...</a> <br><a href="https://link.segmentfault.com/?enc=%2BIgoqOa%2FhFlam7itguXAmg%3D%3D.wtL%2FFq57NDAF16%2BdZ%2BTKL9jYkM6NQgmABXtFZG6aQsumcOSrAJQtxcjZvJ1rMVhX" rel="nofollow">https://www.jianshu.com/p/b37...</a><br><a href="https://link.segmentfault.com/?enc=NVNSkU5rbBHN0kJQvgWy3g%3D%3D.DaKW%2FrumBKfG5JhQD0QdnmUKndViQTzHZk4Q2NRZM449jkcdCBkodT%2BFcpRhkf3RkK3M5F%2BuCqORxw8MOmVIk0jbYOpCnbHNRtUu9SnMjPgmn9s%2FFJ1r00RcHQu10afhhtdOfDGOJMxiBxnx3zEoaQ%3D%3D" rel="nofollow">https://stackoverflow.com/que...</a> <br><a href="https://link.segmentfault.com/?enc=FstvKsK3gaJIFygDmX1jPw%3D%3D.iqyWzR%2FHGRFFcszTaGO7cMB1fONLBlWTVcxG4RxIXgv%2BeuLM9cW2J1VAqiMMkHIu" rel="nofollow">https://www.cnblogs.com/shaos...</a> <br><a href="https://link.segmentfault.com/?enc=QPRMow%2BuHuXqPW6d%2FD8p%2Bw%3D%3D.o6zABfU%2BUrmi32owWtoftHHfP3xr%2BRxrsgHN%2BYP4zpgCr00afjZSTMH%2FjXou0kJQQrLulE9pq566YB2FkXb8xw%3D%3D" rel="nofollow">https://blog.csdn.net/qq27368...</a><br><a href="https://link.segmentfault.com/?enc=38Zelydt6EdQ6G9lp2eKDQ%3D%3D.MvYZnAuZOoFEeJua7%2FaTldsufMWWaLEcxeQkGRpDv5MIDe%2FnnveUuKTlnGYkcUmp" rel="nofollow">https://www.jianshu.com/p/a6f...</a><br><a href="https://link.segmentfault.com/?enc=%2BX3503DmGdn47GEjN7TOOg%3D%3D.PNYFzaz34meHvBXgTl1DO0Ancrch2reZtBNopf4hmvan3gc57PcNp9k6rQT%2BX90K" rel="nofollow">https://github.com/apache/inc...</a><br><a href="https://link.segmentfault.com/?enc=2P4rtt0BREJT1VnQ9STqww%3D%3D.Mm7%2Bv8g4ivDX6JbJ7xJtcMb3LCp8iiUkBDnywVa1U3eArRyiqY66XgHEYTHKp%2Bs8" rel="nofollow">数据可视化平台superset使用心得</a><br><a href="https://link.segmentfault.com/?enc=TUkfQ%2F%2BftsU7tvo1PdauVw%3D%3D.OT47c6f1wJF0q%2BVKR1Ii6ixcvS%2BPaTEBpnn49i5aEBn6iwnX%2F%2BVIu4OI1VeDrQFw" rel="nofollow">一小时建立数据分析平台</a></p>
laravel sentry
https://segmentfault.com/a/1190000016806445
2018-10-25T20:18:50+08:00
2018-10-25T20:18:50+08:00
苏生不惑
https://segmentfault.com/u/sushengbuhuo
8
<h3>注册登录</h3>
<p><a href="https://link.segmentfault.com/?enc=qcyLtAhzZtHpO8TRz0R4dQ%3D%3D.jsIS78s6d%2FBBKqGN2ajOQm1WafMe4vp2hyOIE1GQ%2FlQ%3D" rel="nofollow"> GitHub登录</a><br><img src="/img/bVbgcrL?w=1109&h=554" alt="clipboard.png" title="clipboard.png"></p>
<p>创建project 选择 <a href="https://link.segmentfault.com/?enc=UMJQM5MCCunvKquOfLKWcg%3D%3D.xO91Ce8PJDEfXZpurHMokkyPJYgDbWzQ%2FLj76L%2FPGy14zXu1HWT1Gn1Zp7414kKwtxEPyMVkh1%2FPeqrE7djvjQ%3D%3D" rel="nofollow">laravel</a><br><img src="/img/bVbgcuV?w=1885&h=610" alt="clipboard.png" title="clipboard.png"></p>
<p><img src="/img/bVbgcu1?w=1155&h=558" alt="clipboard.png" title="clipboard.png"></p>
<h3>安装扩展使用</h3>
<p><code>composer require sentry/sentry-laravel</code></p>
<p><code>php artisan vendor:publish --provider="Sentry\SentryLaravel\SentryLaravelServiceProvider"</code></p>
<pre><code class="js">public function report(Exception $exception)
{
if (app()->bound('sentry') && $this->shouldReport($exception)) {
app('sentry')->captureException($exception);
}
parent::report($exception);
}
vi config/sentry.php
return array(
'dsn' => env('DSN'),
// capture release as git sha
// 'release' => trim(exec('git log --pretty="%h" -n1 HEAD')),
// Capture bindings on SQL queries
'breadcrumbs.sql_bindings' => true,
// Capture default user context
'user_context' => false,
//transport function https://docs.sentry.io/clients/php/config/
'transport'=>new \App\SentryTransport(),
);
vi /app/SentryTransport.php
namespace App;
//
class SentryTransport
{
public static function __set_state($array){
return function($raven_client,$data){
\Queue::pushOn('sentry_log',new \App\Commands\sentry($raven_client,$data));
};
}
}
vi app/commands/sentry.php
class sentry extends Command implements SelfHandling, ShouldBeQueued {
use InteractsWithQueue, SerializesModels;
private $raven_client;
protected $data;
/**
* Create a new command instance.
*
* @return void
*/
public function __construct($raven_client, $data)
{
$raven_client->setTransport(null);
$raven_client->close_curl_resource();
$this->raven_client=$raven_client;
$this->data=$data;
}
/**
* Execute the command.
*
* @return void
*/
public function handle()
{
$this->raven_client->send($this->data);//send方法来自 /vendor/sentry/sentry/lib/Raven/Client.php:1019
}
}
vi /vendor/sentry/sentry/lib/Raven/Client.php
public function send(&$data)
{
if (is_callable($this->send_callback)
&& call_user_func_array($this->send_callback, array(&$data)) === false
) {
// if send_callback returns false, end native send
return;
}
if (!$this->server) {
return;
}
if ($this->transport) {
call_user_func($this->transport, $this, $data);
return;
}
// should this event be sampled?
if (rand(1, 100) / 100.0 > $this->sample_rate) {
return;
}
$message = $this->encode($data);
$headers = array(
'User-Agent' => static::getUserAgent(),
'X-Sentry-Auth' => $this->getAuthHeader(),
'Content-Type' => 'application/octet-stream'
);
$this->send_remote($this->server, $message, $headers);
}</code></pre>
<h3>配置dsn</h3>
<p><a href="https://link.segmentfault.com/?enc=TJFShVNawQABrsIXlXpEYw%3D%3D.1h%2Fv6pe9L5Q1H3rkjsBqrNeWylSmo3z5PZEZ1VfQhaMhkr%2BqiWmGFc4Dk%2BOV0puB" rel="nofollow">获取 dsn</a> </p>
<p><img src="/img/bVbiCpG?w=933&h=789" alt="clipboard.png" title="clipboard.png"></p>
<h3>测试</h3>
<p>少写个分号,查看效果<br><img src="/img/bVbgcvi?w=1156&h=495" alt="clipboard.png" title="clipboard.png"></p>
<p><img src="/img/bVbgcvn?w=1222&h=942" alt="clipboard.png" title="clipboard.png"></p>
<h3>monolog 发送到sentry</h3>
<pre><code class="js">composer require monolog/monolog
vi config/app.php
'App\Providers\sentrylog'
vi App\Providers\sentrylog.php
use Monolog\Handler\RedisHandler;
use Monolog\Formatter\JsonFormatter;
use Monolog\Formatter\LineFormatter;
use Monolog\Processor\MemoryPeakUsageProcessor;
use Monolog\Processor\WebProcessor;
use Monolog\Handler\RavenHandler;
class sentrylog extends ServiceProvider {
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot() {
$logger = \Log::getMonolog();
$handler = new RedisHandler($redis, "sentry:monolog", \Monolog\Logger::DEBUG);
$handler->setFormatter(new JsonFormatter(JsonFormatter::BATCH_MODE_NEWLINES, true));
$handler->pushProcessor(new MemoryPeakUsageProcessor(true));
/*$logger->pushProcessor(function ($record) {
$record['extra']['dummy'] = 'Hello world!';
return $record;
});
class MemoryPeakUsageProcessor extends MemoryProcessor
{
/**
* @param array $record 对象当方法调用时执行
* @return array
*/
public function __invoke(array $record)
{
$bytes = memory_get_peak_usage($this->realUsage);
$formatted = $this->formatBytes($bytes);
$record['extra']['memory_peak_usage'] = $formatted;
return $record;
}
}*/
$arr = [
'uri' => 'REQUEST_URI',
'ip' => 'REMOTE_ADDR',
'method' => 'REQUEST_METHOD',
'query_string' => 'QUERY_STRING',
'cookie' => 'HTTP_COOKIE',
'host' => 'HTTP_HOST',
];
$handler->pushProcessor(new WebProcessor(null, $arr));
$logger->pushHandler($handler);
}
/**
* Register the application services.
*
* @return void
*/
public function register() {
//
}
}
vi app/commands/sentry_monolog.php
use Monolog\Handler\RavenHandler;
while (true) {
$data = $redis->lpop("sentry:monolog");
if (!$data) {
sleep(5);
continue;
}
$data = json_decode($data, true);
$raven_client= new \Raven_Client($dsn,['extra' => $data['extra']]);
$raven_hanlder = new RavenHandler($raven_client);
$raven_hanlder->handle($data);//https://pagerefresh.co.uk/apigen/monolog/class-Monolog.Handler.RavenHandler.html vendor/monolog/monolog/src/Monolog/Handler/AbstractProcessingHandler.php:handle vendor/monolog/monolog/src/Monolog/Handler/RavenHandler.php :write
$raven_client->__destruct();
}</code></pre>
<h3>资源</h3>
<p><a href="https://link.segmentfault.com/?enc=4YOwaZio8VFIodHhmBQ81w%3D%3D.soDtpicMxfJSaczxBaPU3pMnUoBxOhjQnIvCqL%2B4dftKJJFvbqzJ9Kyk9MHP0xf5" rel="nofollow">你也可以本地搭建</a><br><a href="https://link.segmentfault.com/?enc=v03McwBDNRrj%2FqVo7rgVGQ%3D%3D.2WFp1okGV3%2B4tsQ3sZrXJHZN1fQfLw3E7H%2FGrwoZLokDYr7t96Ylcz7NKoH3Ba6WLEcwY9Sczv0qRRpmipjIbZDM1e8hS%2BylXi0VJ9Dl7VXNglOTs6aJpv6y6j8lxoodR6k6GHKUZyPmBGbpe3K0Yg%3D%3D" rel="nofollow">Sentry 之部署到生产环境</a><br><a href="https://link.segmentfault.com/?enc=EB1K7jyh4otd4jWSQQF1cQ%3D%3D.Uv7iFaFzJim4DdnWV8W1v%2Bd%2BX5FHwAcxo%2ByLrP%2FfzesHFuHxHi9E2%2BPhFzCndLrLXuTSL8IMz3ewb74x8lRnDpAy%2BDTczR22I4fP3B87CJ8%3D" rel="nofollow">搭建自己的 sentry 服务</a><br><a href="https://link.segmentfault.com/?enc=D1wsOqISBvjUGEsaPLaiQA%3D%3D.MNKkQZcDPmzqyzvimLy3TuGydXpgq03OH5sbrlLPkCf8sWjYY%2Bpq88a90%2F%2BBa2t4iXxTF45IM18ZXqWsxbAAiMs2Vj8qlJbTJbcipsPkJis%3D" rel="nofollow">CentOS6 基于 Python 安装 Sentry</a><br><a href="https://link.segmentfault.com/?enc=TQIlgk1T0NCFXGNbFWpWPQ%3D%3D.2kdFX9vFEaPvxoWO1LT0OV%2BEp3IYfFshzAVzfWUUlzFbe2%2FZca8Meb2yhwUrv8Olc7WCdHg0O4X6PglnMUTkKqjvJsCKfMddM%2FiSHEffnWw%3D" rel="nofollow">Sentry 自动化异常提醒</a><br><a href="https://segmentfault.com/a/1190000007055720">Laravel学习笔记之Errors Tracking神器——Sentry</a><br><a href="https://segmentfault.com/a/1190000012119033">sentry使用</a><br><a href="https://segmentfault.com/a/1190000015308577">利用 entry/onpremise 搭建一个 Sentry 异常汇总工具</a><br><a href="https://segmentfault.com/a/1190000007890855">高效利用Sentry追踪日志发现问题</a><br><a href="https://segmentfault.com/a/1190000002775923#articleHeader4">sentry monolog</a><br><a href="https://link.segmentfault.com/?enc=aBAxMWg7XkFOswSdpJQxvw%3D%3D.HNZ9XwkMta2CzRDjahcdyA10sVmYyqR3FN1RxN22IKakR9ZOtIOPwcchPPW2XMzw4F4%2FroMpiFtu05G9dS0REUYkN3UZjSjWuiQ1y3x49cI%3D" rel="nofollow">Sentry - 处理异常日志的正确姿势</a><br><a href="https://link.segmentfault.com/?enc=%2FECRj2HTRHxWNQlXMFqWMg%3D%3D.Pr1lH20jfIgNKx99N3EoFlInmYQpqNquaMAf0Wy0nQAR5FnquLXgV0IdoSPzZFeh700Z%2BHix%2BKtIZTWp%2BjqGYg%3D%3D" rel="nofollow">Sentry监控Django应用并使用email+钉钉通知</a><br><a href="https://link.segmentfault.com/?enc=8A9m2sLaCK0huunHCuHFJQ%3D%3D.0sBWfXV8biSM5F9mmp%2BYMP1h2Jpi0hFWfS4%2BQW6MfdmvTRPVq30jv3WRxGrI1%2BEP" rel="nofollow">搭建私有的前端监控服务: sentry</a></p>
升级PHP7 jenssegers/mongodb expected to be a reference
https://segmentfault.com/a/1190000016184052
2018-08-28T20:14:39+08:00
2018-08-28T20:14:39+08:00
苏生不惑
https://segmentfault.com/u/sushengbuhuo
7
<blockquote>pecl上的mongodb扩展有两个,都是官方出品的,一个叫mongo,一个是mongodb,前者已经被官方废弃,不再提供稳定的更新,官方推荐使用后者,并且后者是支持php7的。在pecl上搜索mongodb即可找到,也可以通过pecl install mongodb安装。mongo和mongodb的结构完全不同,使用方式也大相径庭,不过官方有个php适配包,可以让mongodb看上去和mongo使用体验近似 <a href="https://link.segmentfault.com/?enc=deXL9wBnl5HEWpnbgEmSlQ%3D%3D.wkhZ5JA2h14lGApRO6Co%2FrKYkXnOzS28m1rptu1ec3v0Np0rE6anpeWNSE82R7dy" rel="nofollow">https://github.com/mongodb/mo...</a>
</blockquote>
<p>以上来自<a href="https://segmentfault.com/q/1010000005753530/a-1020000005753553">这个问题</a> </p>
<p>目前用的 <a href="https://link.segmentfault.com/?enc=zYfR4HhHUWTiEMlEyJgGWg%3D%3D.Fq5f3zRUN9hENt0eIeCz5iIOHQfbZT4nf0%2BhtjxLDbT573LRxOLak7fETpDKzhrw" rel="nofollow">laravel-mongodb</a> </p>
<p><code>WARNING: The old mongo PHP driver is not supported anymore in versions >= 3.0.</code></p>
<p>因为现在用的2.1 版本,而升级PHP7后用的mongodb 扩展,不兼容之前的mongo扩展,所以现在有2个选择:</p>
<p>1.升级到3.0版本。<br>2.使用 <a href="https://link.segmentfault.com/?enc=L7O5JvHGUR6TbCaIpQnjTg%3D%3D.vtjd9fHyXk3nzw1JUjOTJ7hG4iqo3zNg4AwsTWYUn%2BZ98BLPzXj6ATnuV1m0LiCo" rel="nofollow">https://github.com/alcaeus/mo...</a> 作为中间件,不用修改现有代码。</p>
<p>第二个方案来自 <a href="https://link.segmentfault.com/?enc=y5ZfvIK7wgvBqwupSuOUeQ%3D%3D.jnQTgw2z96XbqpJEY4xML%2BSJi3uDFll5grdN4xyS3p8p6B%2Fdy8aeKYnxbivGHo6F" rel="nofollow">http://php.net/manual/zh/set....</a><br>There is an adapter - so old MongoClient / MongoDB code will run on the new PHP7/Mongo mess<br><a href="https://link.segmentfault.com/?enc=55wSa0irybjRyK8aPQhE%2Bw%3D%3D.b%2FQA9BaQA48pWbwuD%2Bo8wO9hX6x%2FnREhKvU3F5WcuAptBFeUiu6AjG5IQjQCVBWG" rel="nofollow">https://github.com/alcaeus/mo...</a></p>
<p>第一个方案就不说了,现在说第二个。</p>
<p><code>composer config "platform.ext-mongo" "1.6.16" && composer require alcaeus/mongo-php-adapter</code></p>
<p>然后测试下 </p>
<p><code>Message::create([ 'title'=>'标题','content'=>'内容22','time'=>time()]);</code><br>提示:</p>
<pre><code class="js">ErrorException in Collection.php line 42:
Parameter 1 to MongoCollection::insert() expected to be a reference, value given</code></pre>
<p>有问题怎么办?当然搜索啊,于是 Google ,不得不说谷歌牛逼,第一条结果就找到了 <a href="https://link.segmentfault.com/?enc=rI9N9yY4Fco%2B%2Fqx%2B27Q1zA%3D%3D.CFlrOBgNa0OHMAEAL0rOzA0I5Qe1EMfAlOUL%2FVPK8t0KbkwSw60lxF6MsUIR4spduhnVu5C6TBe5i6eb0CJtQA%3D%3D" rel="nofollow">https://github.com/alcaeus/mo...</a> </p>
<p><img src="/img/bVbf2BZ?w=966&h=890" alt="clipboard.png" title="clipboard.png"></p>
<p>再看看百度</p>
<p><img src="/img/bVbf2Dc?w=1190&h=933" alt="clipboard.png" title="clipboard.png"></p>
<p>翻不了bing.com 也行啊</p>
<p><img src="/img/bVbf2Dp?w=1058&h=921" alt="clipboard.png" title="clipboard.png"></p>
<p>或者搜 issue</p>
<p><img src="/img/bVbf2Iv?w=911&h=902" alt="clipboard.png" title="clipboard.png"></p>
<p>打开第二个链接 <a href="https://link.segmentfault.com/?enc=nYbxduShbM3AcmraO46GYA%3D%3D.3E7otfFHA6Al8CKm%2BP8fcHNd%2FDnyMpnMi3z5AfOcVeFSp8AxH9h6hYuvkbHh11nJ3xDjoZvtovJPFLLJhJFv3A%3D%3D" rel="nofollow">https://github.com/jenssegers...</a> <br>看最后这个链接 <a href="https://link.segmentfault.com/?enc=8%2B3VO8hq7SosmUcuZ5eikQ%3D%3D.tcqg0qmMraKJE8dEivlWAxcdO8djOtteHwpZ6lYzMWumdYJjun0NvPIJIHmaTmBY5T2egHvpN382GIhSCkC8zP5VW3jEBtL%2BDC5lOFZI6O%2F%2F8zjoi8Cer5IlM3uJdnUL" rel="nofollow">https://github.com/zamrih/lar...</a> </p>
<p><img src="/img/bVbf2FH?w=818&h=284" alt="clipboard.png" title="clipboard.png"></p>
<p>然后修改源文件 <code>jenssegers/mongodb/src/Jenssegers/Mongodb/Collection.php</code> 虽然能解决,但这不是个好的办法。</p>
<pre><code class="js">/**
* Handle specific insert call.
* Cannot be handled dynamically because a reference needs to be passed
* @param array|object $document
* @param array $options
* @return mixed
*/
public function insert(&$document, array $options = [])
{
return $this->__call('insert', array(&$document, $options));
}
/**
* Handle specific batchInsert call.
* Cannot be handled dynamically because a reference needs to be passed
* @param array $a
* @param array $options
* @return mixed
*/
public function batchInsert(array &$a, array $options = [])
{
return $this->__call('batchInsert', array(&$a, $options));
}
/**
* Handle specific save call.https://github.com/zamrih/laravel-mongodb/commit/8c3b4aaaee773e0c2968b4ff215ccec5305394e2
* Cannot be handled dynamically because a reference needs to be passed
* @param array|object $document
* @param array $options
* @return mixed
*/
public function save(&$document, array $options = [])
{
return $this->__call('save', array(&$document, $options));
}</code></pre>
<p>其实 <a href="https://link.segmentfault.com/?enc=Le5mUK4OX%2F2V1vndsOZPzQ%3D%3D.pWCpfGk4Vvs6HPQdcJZBvFLpawjCWzMkW7aM4q4bM9Yzt16VS52UmUj1VBshsBxL" rel="nofollow">https://github.com/alcaeus/mo...</a> 给出提示了<br><code>The insert, batchInsert, and save methods take the first argument by reference. While the original API does not explicitely specify by-reference arguments it does add an ID field to the objects and documents given.</code></p>
<p>接着又出现新问题:<br><code>Fatal error: Call to undefined method MongoDB\Driver\ReadConcern::isDefault() in ..src\Operation\Find.php on line 193</code><br>搜索下 <br><a href="https://link.segmentfault.com/?enc=7Vfps%2FIFHsP8460u5shtBg%3D%3D.eOU3oQnx3z1CPptjxnYDRpRf4ISG484DCvJudHnBgooHtgC%2B9XO3vjv02ohwkYD7IDCLRUoSxARu9QvgD8iEIQ%3D%3D" rel="nofollow">https://github.com/alcaeus/mo...</a> <br><a href="https://link.segmentfault.com/?enc=bd3pC26r73fhVufrXD6MYw%3D%3D.FLUUiBAFVB15o%2F5aOzhTUL21LLewsAc8uHmRNvXypHSUgyHPShFPyv53ahqbmGruRZBRRFt%2F4T4Tv43bbe%2FS0A%3D%3D" rel="nofollow">https://github.com/mongodb/mo...</a> <br><a href="https://link.segmentfault.com/?enc=46pT33mqy0NVDJlhm6%2F9ug%3D%3D.vxDdTHHKCMH1MbGgA%2BPom7EoP3Q9bRsrv0%2F34iMEpcNnnQKTm%2F2b%2BIA8ErgPF1z%2BH4d9u0IXh1hC5AO6XlcMEg%3D%3D" rel="nofollow">https://github.com/mongodb/mo...</a> </p>
<p><a href="https://link.segmentfault.com/?enc=DAkWZ%2FVaW7DazTNNYVJsvg%3D%3D.5C2ulf0AVZG4JZgpSQyZnqfoiQ5PkPMrSdevmmfntdAUP0X6FmjEQo7GTtpXbLbcYdLnxymww0UhkKqsYFfyOqFTV8Izay%2FRwKDVs5YlDUPqt2wr1oYhRivZVa5f2qTp" rel="nofollow">https://github.com/mongodb/mo...</a> 这个提交增加了MongoDBDriverReadConcern::isDefault() 但他要求 MongoDB扩展1.3.0+</p>
<p>因为默认版本是PHP5,所以 pecl install mongodb 会提示</p>
<pre><code class="js">pecl config-show
pecl/mongodb requires PHP (version >= 5.5.0, version <= 7.99.99), installed version is 5.3.29
No valid packages found
install failed
ll /data/php7/bin/
total 124692
-rwxr-xr-x 1 root root 842 Feb 4 2016 pear
-rwxr-xr-x 1 root root 863 Feb 4 2016 peardev
-rwxr-xr-x 1 root root 779 Feb 4 2016 pecl
lrwxrwxrwx 1 root root 9 Feb 4 2016 phar -> phar.phar
-rwxr-xr-x 1 root root 14834 Feb 4 2016 phar.phar
-rwxr-xr-x 1 root root 42332852 Feb 4 2016 php
-rwxr-xr-x 1 root root 42161587 Feb 4 2016 php-cgi
-rwxr-xr-x 1 root root 3583 Feb 4 2016 php-config
-rwxr-xr-x 1 root root 43141643 Feb 4 2016 phpdbg
-rwxr-xr-x 1 root root 4537 Feb 4 2016 phpize
/data/php7/bin/pecl install mongodb</code></pre>
<p>而现在用的是1.1.6版本,那只好升级了 到 <a href="https://link.segmentfault.com/?enc=FYIF7PJ%2FE1TMeFp6ALDDjQ%3D%3D.WjVEuV271lGCoVbxK2QdiK74ab3Z0BCQK1ImTUaHCpGjLJ8O7F4A%2BQmNzZKcpbnH" rel="nofollow">http://pecl.php.net/package/m...</a> 下载最新版本 <a href="https://link.segmentfault.com/?enc=ViNjVxQ4ElJw8fCHF8UX0A%3D%3D.boF49wqomliuutZvwGByHKV3TXIUK8Ifz1GFaekbqb9yIH8mV4f3YRgMrqAcImkC" rel="nofollow">http://pecl.php.net/get/mongo...</a></p>
<pre><code class="js">tar -zxf mongodb-1.5.2.tgz
cd mongodb-1.5.2
which php7
/data/php7/bin/phpize
which php-config
./configure --with-php-config=/data/php7/bin/php-config
make && make install
ll /data/php7/lib/php/extensions/no-debug-zts-20151012/
php7 -i |grep extension_dir
extension_dir => /data/php7/lib/php/extensions/no-debug-zts-20151012 => /data/php7/lib/php/extensions/no-debug-zts-20151012
sqlite3.extension_dir => no value => no value
php7 --ini
Configuration File (php.ini) Path: /data/php7/etc/
Loaded Configuration File: /data/php7/etc/php.ini
Scan for additional .ini files in: (none)
Additional .ini files parsed: (none)
vi /data/php7/etc/php.ini
extension=mongodb.so
php7 -m |grep mongodb
php7 -i|grep mongodb</code></pre>
<p>链接:<br><a href="https://link.segmentfault.com/?enc=9T46ialxrHjw37lSWVPfaA%3D%3D.BrWB8li4%2BbFZ0Gg4CFjFynQ4aVk6U8bPdkge%2FsQtbNs19OqnMJiLyfDMxIBRr%2FbK39wlIyq7lLuwKCT4xMVCGQ%3D%3D" rel="nofollow">https://github.com/alcaeus/mo...</a><br><a href="https://link.segmentfault.com/?enc=smUBLWZOvBWxubqOq5d7nQ%3D%3D.Moq2tNmgC9pYg%2BEhq4haScuvb%2FWHQPR7aIB1jB%2BvPi3W%2BCEddnLx%2B8JxdZ6Z0dZZUm86A%2FY3qchh3efeOu15Zg%3D%3D" rel="nofollow">https://github.com/mongodb/mo...</a><br><a href="https://link.segmentfault.com/?enc=8ZJjkWpefpYh%2F4U9wo1BUA%3D%3D.vGVJ7c8aArclqDLnV3xnzx2D770ijlAAb0FGd6SLAOQv18wmA8iQ3OHNy3oSi2UFkbNE%2FI0MeEsNkcenUfJThmymMtvqW2PaH%2BzEm2heH%2FE1XCPJi7VSsN3uRtbcu%2F7MN7K31kh0gvgrdL3e6tHRrw%3D%3D" rel="nofollow">https://github.com/alcaeus/mo...</a><br><a href="https://link.segmentfault.com/?enc=WHxhwKGt9mefnLxhe7ZrpQ%3D%3D.pwwtrojWOLFlGsbeUC6zScHcfHkvg6iYQIkp3%2BilSdpp44GRuKiPtukm3AbAzK%2BOBB61Uvtp%2BUZud0y1cppuhQ%3D%3D" rel="nofollow">http://php.net/manual/en/mong...</a> <br><a href="https://link.segmentfault.com/?enc=h1nOnxKWkR9rwVBCJb20Cg%3D%3D.CvXLZT49WeMA0leM35qPdwODb%2BwU%2BxAS8zqcyCTKESe9M5Xf0%2BtC2a%2BXNlCk1Gp4ZjV5EK7Ae7TZRFmRuKVGlA%3D%3D" rel="nofollow">http://php.net/manual/zh/mong...</a> <br><a href="https://link.segmentfault.com/?enc=b09oI0lVjoJ2gepppJJ0xA%3D%3D.evXC3N1bQCQ%2F5AwZ6g2%2F6y4Yvu4T984YXUYZ1cT7g8pz3oB6i3ktVh%2BLuNmCk4zu" rel="nofollow">http://php.net/manual/zh/set....</a> <br><a href="https://link.segmentfault.com/?enc=pu8fHKbjAIBcQjSajFhklA%3D%3D.TIsnGmyh1gysSf40rESI1XN442KOKQOgFgCFlRRQclqJiY8uqMdAu6M0Ohbhjpb6" rel="nofollow">https://github.com/mongodb/mo...</a><br><a href="https://link.segmentfault.com/?enc=QrQLyLcgBMflc%2F7TdV3IUw%3D%3D.S4jE%2FZJ7tvNGHLWhSNWDRHas%2BFluKXKDXRJxIA6%2B3phAfO0v%2Bs5VW8dRI4LLYh3QvW8OOp%2Bvs5DX%2BdYFaakFUS%2Fq1p6XR9c1D9D8fgT%2BGaM%3D" rel="nofollow">https://secure.php.net/manual...</a><br><a href="https://link.segmentfault.com/?enc=OnoSnAEI3dJAoZYffKD9rg%3D%3D.96kemOmv4MzWj%2BM%2FILF1zm7%2FOpbhDgG%2Fdgmsy0weLqQEXFHVC73LHd5l5XMOxBrynhCVHD0UtlxCmwLAOt3G1A%3D%3D" rel="nofollow">https://github.com/mongodb/mo...</a><br><a href="https://link.segmentfault.com/?enc=Sfci9bqkYnOJhVLiPuKEDg%3D%3D.Jf5NKYCDqIolvlrdgVTAAvxJ41wa%2FQiGwqcTMY%2FzVDcAZ2FrjoLcpS%2FVGtUvEH1GD%2Bp0ZzGB72hTqbTwA3226Q%3D%3D" rel="nofollow">https://github.com/alcaeus/mo...</a><br><a href="https://link.segmentfault.com/?enc=VImeKrugTzwjm5aFEsCO8w%3D%3D.YiCfO6cs99XF4aT8cY%2FWOWm8ojCRhbzoPC247EMbSXRunJ7856PsWWTYqm6L%2FHqR" rel="nofollow">pecl 更换对应php版本</a><br><a href="https://link.segmentfault.com/?enc=8lplad6uFUYSbMPMVwKfrw%3D%3D.2xEGmQihTX10ialSE%2BTflgY1BWtVY5MzKl91QRSsaoQjyqKz6CJAhN4rexyKIY70AbkodA5uBz1nXr044dDfr9bfEE0tw%2F9BSMIAELrZ8K9YRxaeyUwgbIfx8dZEio6ZPYAyDm6stupWOJdVdt1OzjUednNqkVLRiaaVKLx%2Fb6c%3D" rel="nofollow">车轮升级PHP7踩过的一些坑 </a> <br><a href="https://link.segmentfault.com/?enc=e2c5X2qYpP8UrAK3WPH41w%3D%3D.%2FggUFRPjSa0cSfRSh4OQPcZXJw0HcauiZA5kBZJ286FNBMxIby6x3cQOOD6UXUG2lC08exgke5bX4lIdyfRqmg%3D%3D" rel="nofollow">《PHP 开发者实践》</a><br><a href="https://link.segmentfault.com/?enc=ZxzvRrm4Pc%2FS%2BoA3Dt9ncw%3D%3D.%2FtCda79gm1OSEaT%2BWZqpemBRsizHILrjMmK4juDSCa0AUXxNR6vJTArs1e05vObyWnJo0FmZ0n55Tv06nXXg9w%3D%3D" rel="nofollow">PHP 手册拾遗</a><br><a href="https://link.segmentfault.com/?enc=20mbGENuxGevzbsLVGHtug%3D%3D.A7Q5wpu8vIAcMw7yEzrbsLpGVhwv4bOmS0ZE4seOfe6tcfcvAHxe9MH5sa6RIoQkqkePc7Rm3HKFYbFwcXyhp6Dik7538h%2BhbHax3FUCud2EZbF0Sh1fGypnn0ryCgrxpJ%2BqmwTm%2F8vTqyTMLp2QcdEfoZ%2BQGqmLpiQweQ3yofqDn9YXwbtUdOYpVU8UQWejVA4Cipl5ikkrF9VBpOQTbnhIekfAHAO09w2a721FkVjpTDuvDXpWjYYFv2v6M7nQz%2F18gG3pgZfwEkI%2FrCpI3qZ%2BbjUNOXwqKvupe%2FNYz0MBjzdHwzsvMXu%2FNyX5M2CapMfbm6ebJeAhads5Vv9THsp7WVf4NITLyG%2BaDScVafp3oHdrc%2Fb6svggGQIwFA7i%2FYO3a%2BivJqIWgiyGI3PwjADqS18XZXzDPHH%2Bc0JrDuf1%2FCuQJEtLfA%2FZt4xGxUUxjIeVttFaQfp%2Bx0oIQIKFqDT9mqZBND3juhiJX2BRhyQCHQBPpRu%2F%2BioykYyo8ow1PJGdz%2Fg7RtTnUKsvnre6ckcLCXHQVZwVPA%2F9lh7TwNHIXvmF2mbYlBxabieOgUDwjfgIEr%2FDg2mvnic%2BKgludV2ZRkEbzJezx3Y1bKzyq80pLuJRjF5Q3BQ10CjLMEXDDXpLCRDyiO0QJDd4UhtPQ7k6ldQYFrp%2BXgKavR8Vn8EVpmyPPb51QQi3JlTqWMArhnIhtaG%2FU5UGypCMGnJwIA%3D%3D" rel="nofollow">PHP 7 升级实践</a><br><a href="https://link.segmentfault.com/?enc=dNQbXNNBVr9hxyHATgRFbg%3D%3D.xy8AwPUbvEhZrDBHHn97JL2tXAiRCeIrmhgU7MTliIu2J1nf7EBrLQyXQ4SU%2FKrB" rel="nofollow">php7cc 辅助进行代码检查</a><br><a href="https://segmentfault.com/a/1190000013837897">php5 php7不兼容的地方</a><br><a href="https://link.segmentfault.com/?enc=XNRXm9%2FxYMWgAqXNB7R6cA%3D%3D.do%2BbYpSVxvNSazTehuSkVFsRcO4gUF6AA9mkM51vMs3DUzQrm9AeskCqIGQTk%2BYs0zo9A77SqgVIbHMrwxIhpQ%3D%3D" rel="nofollow">PHP7内核剖析</a><br><a href="https://segmentfault.com/a/1190000015738271">升级PHP7操作MongoDB</a><br><a href="https://link.segmentfault.com/?enc=8IJt8aenE7bZKE9NaEM1rA%3D%3D.B2gb854K26vFV%2Fa6rcg5uBsV2HkXh5WonBjuWSOISxCU%2F4eFsaz7zice8xvCTbPBVaEbVby0%2BhJVeGt3RmLkuw%3D%3D" rel="nofollow">一篇写给准备升级PHP7的小伙伴的文章</a></p>
PHP hash 接口对接
https://segmentfault.com/a/1190000012922186
2018-01-21T14:01:11+08:00
2018-01-21T14:01:11+08:00
苏生不惑
https://segmentfault.com/u/sushengbuhuo
3
<p>最近接一个项目,需要调用对方接口生成 token 但只提供了 node 版,源代码如下</p>
<pre><code class="js">//https://blog.zhengxianjun.com/2015/05/javascript-crypto-js/
npm install crypto-js
var CryptoJS = require('crypto-js')
calSignature = function (toSign, key) {
var hash, hex, signed;
hash = CryptoJS.HmacSHA1(toSign, key);
hex = hash.toString(CryptoJS.enc.Hex);
signed = base64.encodeBase64(hex);
return signed;
};
var hmacSHA1 = CryptoJS.HmacSHA1("Message", "Secret Passphrase").toString(CryptoJS.enc.Hex);
console.log(hmacSHA1) ;//e90f713295ea4cc06c92c9248696ffafc5d01faf
也可以在线测试 https://blog.zhengxianjun.com/online-tool/hash/
<script src="cryptojs/rollups/md5.js"></script>
var str = '123456';
CryptoJS.MD5(str);
<script src="cryptojs/rollups/hmac-sha1.js">
</script>
<script src="cryptojs/rollups/hmac-sha3.js">
</script>
<script src="cryptojs/rollups/hmac-sha224.js">
</script>
<script src="cryptojs/rollups/hmac-sha256.js">
</script>
var str = '123456';
var password = 'password';
// Hmac 相关调用前都增加了 Hmac
CryptoJS.HmacMD5(str, password);
CryptoJS.HmacRIPEMD160(str, password);
CryptoJS.HmacSHA1(str, password);</code></pre>
<p>但是我们的项目是基于 PHP 于是有了</p>
<pre><code class="js">$sign = base64_encode(hash_hmac('sha1', $sign, $key)); </code></pre>
<p>果然 PHP 是最好的语言,一句话搞定。</p>
<p>另外说到请求对方接口的问题,对方要求传递一个 json 参数过去,比如</p>
<pre><code class="js">$url = 'xxxxx.com';
$data = ['limit' => ['start' => 0, 'end' => 5]];
$res = curlGet($url.'/api/?'.json_encode($data);</code></pre>
<p>结果提示 fail Malformed HTTP request line<br>但是 python get 没问题</p>
<pre><code class="js">res = requests.get(url, params=data, headers=headers)</code></pre>
<p>于是对参数再进行一次 base64</p>
<pre><code class="js">$res =curlGet($url.'/api/?'.base64_encode(json_encode($data));</code></pre>
<p>但对方有时候接受的参数 base64 解析出错</p>
<pre><code class="js">>>> s='eyJsaW1pdCI6eyJzdGFydCI6MCwiZW5kIjo1fSwidGFibGVfbmFtZSI6Im9ubGluZV91dl9hY
2NvdW50X2lkXzFob3VyX2FuYWx5c2lzX2RhdGEiLCJmaWx0ZXJfYXJncyI6eyJ2ZmlkIjoiMTQiLCJ0a
W1lc3RhbXBfMWhvdXIiOiIyMDE4LTAxLTA1IDIwOjA0OjI2In0sImJpel9kZXMwMSI6MCwib3JkZXJfY
nkiOiJ0aW1lc3RhbXBfMWhvdXIifQ'
>>> base64.b64decode(s)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "d:\python27\lib\base64.py", line 76, in b64decode
raise TypeError(msg)
TypeError: Incorrect padding
>>> base64.b64decode(s+'===')
'{"limit":{"start":0,"end":5}'
于是有了如下处理
def decode_base64(data):
missing_padding = len(data) % 4
if missing_padding != 0:
data += b'='* (4 - missing_padding)
return base64.decodestring(data)</code></pre>
<p>传递时也改成 安全 base64</p>
<pre><code class="js">function urlsafe_b64encode($string) {
$data = base64_encode($string);
$data = str_replace(array('+','/','='),array('-','_',''),$data);
return $data;
}
function urlsafe_b64decode($string) {
$data = str_replace(array('-','_'),array('+','/'),$string);
$mod4 = strlen($data) % 4;
if ($mod4) {
$data .= substr('====', $mod4);
}
return base64_decode($data);
}
$res =curlGet($url.'/api/?'.urlsafe_b64encode(json_encode($data));</code></pre>
网易云易盾验证码
https://segmentfault.com/a/1190000012259934
2017-12-03T12:20:16+08:00
2017-12-03T12:20:16+08:00
苏生不惑
https://segmentfault.com/u/sushengbuhuo
1
<p>之前用的图形验证码,现在改用网易云滑动验证码,<a href="https://link.segmentfault.com/?enc=poUCA%2FoumKO%2F1ezmWr7nhA%3D%3D.Ccq6oOvRddM%2FnA%2BWsT7g5lLkLTAS31LuqSDgXX8Cc2LMNf32w3mlTbkKcqz3jZBrw9QBWLtsjiSYfEMR4brjVZzSvhanJn4wWqctCsw3XFc%3D" rel="nofollow">效果如下</a> 这里基于 laravel 来实现</p>
<p><img src="/img/bVZBvV?w=402&h=443" alt="clipboard.png" title="clipboard.png"></p>
<h3>校验验证码</h3>
<pre><code class="js">vi App\Services\CaptchaVerifier.php
<?php
namespace App\Services;
/**
* 易盾验证码二次校验SDK
*
*/
class CaptchaVerifier {
const VERSION = 'v2';
const API_TIMEOUT = 5;
const API_URL = 'http://c.dun.163yun.com/api/v2/verify';
/**
* 构造函数
* @param $captcha_id 验证码id
* @param $secret_id 密钥对
* @param $secret_key 密钥对
*/
public function __construct($captcha_id, $secret_id, $secret_key) {
$this->captcha_id = $captcha_id;
$this->secret_id = $secret_id;
$this->secret_key = $secret_key;
}
/**
* 发起二次校验请求
* @param $validate 二次校验数据
* @param $user 用户信息
*/
public function verify($validate, $user = '') {
$params = array();
$params["captchaId"] = $this->captcha_id;
$params["validate"] = $validate;
$params["user"] = $user;
// 公共参数
$params["secretId"] = $this->secret_id;
$params["version"] = self::VERSION;
$params["timestamp"] = sprintf("%d", round(microtime(true)*1000));// time in milliseconds
$params["nonce"] = sprintf("%d", rand()); // random int
$params["signature"] = $this->sign($this->secret_key, $params);
$result = $this->send_http_request($params);
return array_key_exists('result', $result) ? $result['result'] : false;
}
/**
* 计算参数签名
* @param $secret_key 密钥对key
* @param $params 请求参数
*/
private function sign($secret_key, $params){
ksort($params); // 参数排序
$buff="";
foreach($params as $key=>$value){
$buff .=$key;
$buff .=$value;
}
$buff .= $secret_key;
return md5($buff);
}
/**
* 发送http请求
* @param $params 请求参数
*/
private function send_http_request($params){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, self::API_URL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, self::API_TIMEOUT);
curl_setopt($ch, CURLOPT_TIMEOUT, self::API_TIMEOUT);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
/*
* Returns TRUE on success or FALSE on failure.
* However, if the CURLOPT_RETURNTRANSFER option is set, it will return the result on success, FALSE on failure.
*/
$result = curl_exec($ch);
// var_dump($result);
if(curl_errno($ch)){
$msg = curl_error($ch);
curl_close($ch);
return array("error"=>500, "msg"=>$msg, "result"=>false);
}else{
curl_close($ch);
return json_decode($result, true);
}
}
}</code></pre>
<h3>新建 ServiceProvider</h3>
<pre><code class="js">vi App\Providers\CaptchaServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App\Services\CaptchaVerifier;
class CaptchaServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*/
public function boot()
{
$this->app['validator']->extend('captcha', function($attribute, $value, $parameters)
{
return (new CaptchaVerifier(config('captcha.captcha.CAPTCHA_ID'),config('captcha.captcha.SECRET_ID'),config('captcha.captcha.SECRET_KEY')))->verify($value);
});
}
/**
* Register any application services.
*
* This service provider is a great spot to register your various container
* bindings with the application. As you can see, we are registering our
* "Registrar" implementation here. You can add your own bindings too!
*/
public function register()
{
}
}
vi config/app.php
'providers' => [
'App\Providers\CaptchaServiceProvider',
]
vi config/captcha.php
#联系商务获取秘钥
'captcha'=>[
'CAPTCHA_ID' => 'xxxxx',
'SECRET_ID' => 'xxxxx',
'SECRET_KEY' => 'xxxxx',
]</code></pre>
<h3>调用</h3>
<pre><code class="js">use Illuminate\Http\Request;
public function postLogin($q Request){
$this->validate($q, [
'captcha' => 'required|captcha',
]);
return response()->json(['code' => '200', 'msg' => 'success'])
}
</code></pre>
<p><a href="https://link.segmentfault.com/?enc=12PcpWh6Vv4nsyQm%2FxUjfA%3D%3D.wz5d9%2FqF%2BLa86QMMC8sFLuESVDQAU5ld1nyh1vluenVN%2BjLtlYZMZS0NTeTv5lt0" rel="nofollow">文档地址</a><br><a href="https://link.segmentfault.com/?enc=TqYN7KoOyku8Shm1VCfabg%3D%3D.CG%2F5PjJZeJrkXPfW0Ysnxg3K1m3TPskxhjpxWgcGdM8dX1j2SsFhF%2BJX7T9MkH1R" rel="nofollow">demo</a><br><a href="https://link.segmentfault.com/?enc=if2%2B7Gjra4FDoWmwt%2BqKFQ%3D%3D.dGurezdORfHz7ye0BvjkjFhamsGuiWRSYF1qZjdbtypsE7qgcOHx36RwZVFL%2BFnA" rel="nofollow">类似的极验验证码</a></p>
laravel 发送带附件的邮件
https://segmentfault.com/a/1190000011857370
2017-11-04T16:27:10+08:00
2017-11-04T16:27:10+08:00
苏生不惑
https://segmentfault.com/u/sushengbuhuo
3
<p>有时候需要给运营定时发送表格数据,方式是定时跑程序将数据生成一个 excel 然后邮件发送到运营邮箱,这里用 laravel 来处理.</p>
<h3>安装 maatwebsite/excel</h3>
<pre><code class="js">composer reuqire maatwebsite/excel</code></pre>
<h3>下载 excel</h3>
<pre><code class="js"> $titles = [
'用户ID', '用户昵称', '公司名称', '销售', '功能版本', '次数', '最高', '消耗', '剩余', '时间'
];
//使用 Excel::create
$data_arr=[$titles,['user_id'=>100,'nick_name'=>'xxx','company'=>'百度','seller_name'=>'老王','user_type'=>1,'times'=>666,'top'=>100,'flows'=>88,'rest'=>123,'time'=>date('YmdHis')]];//从数据库读取的结果
//http://www.maatwebsite.nl/laravel-excel/docs/export
\Excel::create('excel', function($excel) use($data_arr){
$excel->sheet('Sheetname', function($sheet) use($data_arr) {
$sheet->fromArray($data_arr, null, 'A1', false, false);
});
})->store('xlsx',storage_path('excel/exports'));</code></pre>
<p><img src="/img/bVXUNA?w=724&h=231" alt="clipboard.png" title="clipboard.png"></p>
<h3>发送邮件</h3>
<pre><code class="js">// https://docs.golaravel.com/docs/5.0/mail/ 邮件配置参考
#cat .env
MAIL_DRIVER=smtp
MAIL_HOST=smtp.exmail.qq.com
MAIL_PORT=25
MAIL_USERNAME=xxx@xxx.com
MAIL_PASSWORD=xxx
#cat config/mail.php
//模板文件
#cat resources/views/emails/attachment.balde.php
附件内容:{{$content}}
<br>
发送时间:{{date('Y-m-d H:i:s')}}
//重试 3次
$tryTimes=3;
do {
$email='xxx@xx.com';
$attachments=['file'=>storage_path('excel/exports').'/excel.xlsx'];//上面下载的 excel 附件
$subject='mail';
$cc='xxx@xx.com';//抄送邮件
$sendResult = \Mail::send('emails.attachment', ['content' => '发送内容'], function ($message) use ($email, $attachments, $subject, $cc) {
$message->to($email)->subject($subject);
foreach ($attachments as $alias => $attachment) {
$ext = pathinfo($attachment)['extension'];
$message->attach($attachment, ['as' => "=?UTF-8?B?" . base64_encode($alias) . "?=." . $ext]);//
}
if (!empty($cc)) {
$message->cc($cc);
}
});
$tryTimes--;
} while ($sendResult == 0 && $tryTimes);
dd($sendResult);//发送成功 2</code></pre>
网页转图片
https://segmentfault.com/a/1190000011559379
2017-10-15T10:50:21+08:00
2017-10-15T10:50:21+08:00
苏生不惑
https://segmentfault.com/u/sushengbuhuo
5
<p>将一段文字转成图片,比如常用的<a href="https://link.segmentfault.com/?enc=1k0NjSrPMiI69ybXATUwpA%3D%3D.1X7yEOCTxCq0BNzG8zZLct%2B6kkTC%2FFXjPCCgcUd%2B6EY%3D" rel="nofollow">长微博工具</a> 这里用 PHP 来处理。</p>
<h3>text2pic</h3>
<pre><code class="js">composer require dsgygb/text2pic
touch test.php
<?php
require 'vendor/autoload.php';
$transform = new Text2pic\Transform('by text2pic');
$result = $transform->generate("hello world");
print_r($result);
#中文字体路径 /c/windows/fonts/sihei.ttf
$transform=new Text2pic\Transform($by,$uploadsPath,$uploadsUrl,$fontPath);</code></pre>
<p><img src="/img/bVWFho?w=659&h=1151" alt="clipboard.png" title="clipboard.png"></p>
<h3>wkhtmltopdf</h3>
<p><a href="https://link.segmentfault.com/?enc=8ZpKfp8E7JHgdptql1Aa%2Bg%3D%3D.tmBxgfWo2rV0R8aZPjkfi%2BqhzB9WCntee0LG5inkcv11yufetbQkL88Tynd7soLz" rel="nofollow">地址</a> 下载后有 2 个工具 wkhtmltoimage 和 wkhtmltopdf 分别是将网页转图片和pdf 的,<a href="https://link.segmentfault.com/?enc=6aImlYtMeUv5sYT30m%2FRsQ%3D%3D.2T7at5Rw3MGdgVStswRYswhvL91iLnYSC2TKiniRdTt%2F5lPgiYG4mbqcWoa2WM7zdW4mCtUaLB3xI1LllAylZA%3D%3D" rel="nofollow">具体使用参考</a></p>
<pre><code class="js">#生成图片 https://gist.github.com/vibbow/5702882
/user/bin/wkhtmltoimage http://www.baidu.com/ baidu.jpg
#php 调用 使用绝对路径
$r=shell_exec("/user/bin/wkhtmltoimage http://www.baidu.com/ baidu.jpg");
$r=shell_exec("/user/bin/wkhtmltoimage -q {$filename}.html {$filename}.jpg");
</code></pre>
<h3>phpwkhtmltopdf</h3>
<pre><code class="js"># 一个 PHP 库 https://github.com/mikehaertl/phpwkhtmltopdf
composer require mikehaertl/phpwkhtmltopdf
require './vendor/autoload.php';
use mikehaertl\wkhtmlto\Image;
// You can pass a filename, a HTML string, an URL or an options array to the constructor
$image = new Image('/path/to/page.html');
$image->saveAs('/path/to/page.png');//保存
// ... or send to client for inline display
$image->send();//浏览器显示
// ... or send to client as file download
$image->send('page.png');//浏览器显示并下载
#另外一个库 https://github.com/knplabs/snappy
use Knp\Snappy\Pdf as newpdf;
$snappy = new newpdf('wkhtmltopdf');
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="file.pdf"');
// echo $snappy->getOutput('http://www.github.com');
$snappy->generateFromHtml('<h1>Bill</h1><p>You owe me money, dude.</p>', 'bill-123.pdf');
</code></pre>
<h3>more</h3>
<pre><code class="js">小人举牌图片生成 https://github.com/jokin1999/HoldUpSign
https://stackoverflow.com/questions/5663814/how-do-i-get-wkhtmltopdf-to-execute-via-php
http://www.jianshu.com/p/4d65857ffe5e
http://yuncode.net/code/c_51dd01a4d547f26
https://github.com/niklasvh/html2canvas
网页保存为图片及高清截图的优化https://segmentfault.com/a/1190000011425316</code></pre>
命令行获取公网 IP
https://segmentfault.com/a/1190000010865949
2017-08-26T16:57:38+08:00
2017-08-26T16:57:38+08:00
苏生不惑
https://segmentfault.com/u/sushengbuhuo
5
<p>本文收集了一些获取公网 ip 的方法,也欢迎你评论分享</p>
<h3><a href="https://link.segmentfault.com/?enc=u6UE%2BuJcOD8OCOCwQqI7QQ%3D%3D.nIj4sc%2BsRMzF9E9%2F%2By6om7sYP1SJCzY6x5cGyc%2BnQXU%3D" rel="nofollow">curl ipinfo.io</a></h3>
<pre><code class="js">$ curl ipinfo.io
{
"ip": "36.10.25.4",
"city": "Hangzhou",
"region": "Zhejiang",
"country": "CN",
"loc": "30.2936,120.1614",
"org": "AS4134 CHINANET-BACKBONE"
}</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=UcdbNpeZg3cHzqEQ2XsfPQ%3D%3D.quv1YtpC5EnVVio0Vy1A0Zcq6fBs1rLl6Zk9t7dRVKQ%3D" rel="nofollow">curl httpbin.org/ip</a></h3>
<pre><code class="js">$ curl httpbin.org/ip
{
"origin": "36.10.25.4"
}</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=4%2FK3g9NgqxlzZdlzo0U%2FrQ%3D%3D.JFZGMoVm9peQsZp8%2B7UtJ84afopPHtOgl3%2FKjngKcXg%3D" rel="nofollow">curl myip.ipip.net</a></h3>
<pre><code class="js">$ curl myip.ipip.net
当前 IP:36.10.25.4 来自于:中国 北京 北京 鹏博士</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=BjxZDzBQRdeXjWvllEIk8g%3D%3D.5PRqshrEpm%2BEJ8FR2GkxPw%3D%3D" rel="nofollow">curl ip.sb</a></h3>
<pre><code class="js">$ curl ip.sb
36.10.25.4</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=Pa2ZWyHnmXXpZU2iZC5q3w%3D%3D.YayD8RPuBBps352luFvFun4O332XC73EGR0%2FGeVvMwY%3D" rel="nofollow">curl -s ifcfg.cn/echo |python -m json.tool</a></h3>
<pre><code class="js">$ curl -s ifcfg.cn/echo |python -m json.tool
{
"url": "http://ifcfg.cn/echo",
"user_agent": "curl/7.30.0",
"protocol": "http",
"query_string": "",
"ip": "36.10.25.44",
"headers": {
"CONNECTION": "close",
"HOST": "ifcfg.cn",
"ACCEPT": "*/*",
"USER-AGENT": "curl/7.30.0"
},
"location": "\u4e2d\u56fd \u5317\u4eac",
"method": "GET",
"path": "/echo",
"host": "ifcfg.cn"
}</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=ReKPK2WAKSaD2LiR1vkImw%3D%3D.ck45nYq%2BkMbvrU3xajkbW0WInBCA6Szd0k5LmjBemmE%3D" rel="nofollow">curl ifconfig.me</a></h3>
<pre><code class="js">$ curl ifconfig.me
36.10.25.4</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=o5eIBPrQrkYZQaimTtr%2Bww%3D%3D.ZOiuI%2FwXoErjcOE%2BnVbFQR%2BsW26a04F4Bea0b%2FtlCpk%3D" rel="nofollow">curl ifconfig.io</a></h3>
<p><code>curl ifconfig.io</code></p>
<h3><a href="https://link.segmentfault.com/?enc=V8cmQqXNolfqs7XpZkEiHg%3D%3D.ihn2ahBL3iCGglX%2B7jAhkfGUn1XZ%2Bn8shbf5qlS40lo%3D" rel="nofollow">curl https://whatip.ga</a></h3>
<p><code>curl https://whatip.ga</code></p>
<h3><a href="https://link.segmentfault.com/?enc=CiciMFpuz7z%2BuYT7fsgSWA%3D%3D.mb%2BHt05x2KBwu5Da%2Bm1z63bZ9fd81hYLI1EjBlfRlok%2FAP62AksGKM%2BAabhh5Ed8TvRN1tLYRtxU4wgycWYoVQ%3D%3D" rel="nofollow">curl http://ip.taobao.com/service/getIpInfo2.php?ip=myip</a></h3>
<pre><code class="js">$ curl -s http://ip.taobao.com/service/getIpInfo2.php?ip=myip|python -m json.to
ol
{
"code": 0,
"data": {
"country": "\u4e2d\u56fd",
"country_id": "CN",
"area": "\u534e\u5317",
"area_id": "100000",
"region": "\u5317\u4eac\u5e02",
"region_id": "110000",
"city": "\u5317\u4eac\u5e02",
"city_id": "110100",
"county": "",
"county_id": "-1",
"isp": "\u9e4f\u535a\u58eb",
"isp_id": "1000143",
"ip": "36.10.25.44"
}
}</code></pre>
<p>ps:返回的 ip 我已修改过,奇怪的是这些方法返回 2 种地址,比如第一个<code>curl ipinfo.io</code> 就不准</p>
PHP 那些“坑”
https://segmentfault.com/a/1190000010748235
2017-08-19T19:48:15+08:00
2017-08-19T19:48:15+08:00
苏生不惑
https://segmentfault.com/u/sushengbuhuo
50
<p>本文持续更新,欢迎关注</p>
<h3><a href="https://link.segmentfault.com/?enc=SLrwQK4r2AH5P0J5xVo1Ng%3D%3D.oMUbJgxE4gXppCw%2BxYVhv2bkBqch47N7maVofJu4WpK4RVJ1xp5%2BdyWPGPzjTm85AfZg8kH7Lx8eYXeme3%2BQmQ%3D%3D" rel="nofollow">字符串 == 比较类型强转隐患</a></h3>
<pre><code class="js">// php 5
var_dump(md5('240610708') == md5('QNKCDZO'));//bool(true)
var_dump(md5('aabg7XSs') == md5('aabC9RqS'));//bool(true)
var_dump(sha1('aaroZmOk') == sha1('aaK1STfY'));//bool(true)
var_dump(sha1('aaO8zKZF') == sha1('aa3OFF9m'));//bool(true)
var_dump('0010e2' == '1e3');//10×10^2 = 1×10^3 bool(true)
var_dump('0x1234Ab' == '1193131');//bool(true)
var_dump('0xABCdef' == ' 0xABCdef');//bool(true)
var_dump("603E-4234" == "272E-3063");//bool(true)
var_dump('0e1' == '0e2'); //bool(true)
// php 7 含十六进制字符串不再被认为是数字 http://php.net/manual/zh/migration70.incompatible.php
var_dump('0x1234Ab' == '1193131');//bool(false)
var_dump('0xABCdef' == ' 0xABCdef');//bool(false)
var_dump("0x123" == "291");//bool(false)
var_dump(is_numeric("0x123"));//bool(false)
>>> md5('240610708')
=> "0e462097431906509019562988736854"
>>> md5('QNKCDZO')
=> "0e830400451993494058024219903391"
// php 是弱语言,会自动判断数据类型,0eXXXXXXXXXX 转成 0 了
//来自文档:如果比较一个数字和字符串或者比较涉及到数字内容的字符串,则字符串会被转换为数值并且比较按照数值来进行。此规则也适用于 switch 语句。当用 === 或 !== 进行比较时则不进行类型转换,因为此时类型和数值都要比对。
>>> md5('QNKCDZO')==0
=> true
>>> md5('240610708')==0
=> true
// 使用 === 判断 官方都建议直接用password_hash加密
var_dump(md5('240610708') === md5('QNKCDZO'));//bool(false)
//http://bayescafe.com/php/yuebaomei-ctf.html
var_dump("42"=="0x2A");//bool(true)
var_dump("1" == "01"); // 1 == 1 -> true
var_dump("10" == "1e1"); // 10 == 10 -> true
var_dump(100 == "1e2"); // 100 == 100 -> true
var_dump("\x34\x32\x2E"=="42");//bool(true)
var_dump("\001abc");//abc
var_dump('\001abc');//\001abc
$a = "1234567";
var_dump($a['test']);//1
var_dump(in_array(false, array('xxx')));//false
empty('0');//false
"133" == "0133";
133 == "0133";
133 == 0133; //因为0133是一个八进制数,转成十进制是91
"0133" != 91; //字符串中的数字始终是十进制的,这个也可以理解
"0x10" == 16; //但是!,在十六进制中上面的说法又不成立了
"1e3" == 1000; //科学计数表示也一样
#'string' == true,而且'string' == 0,但是,true != 0
null == 0;
null < -1;
$flag = "THIS IS FLAG";
if ("POST" == $_SERVER['REQUEST_METHOD'])
{
$password = $_POST['password'];//420.00000e-1
if (0 >= preg_match('/^[[:graph:]]{12,}$/', $password))
{
echo 'Wrong Format';
exit;
}
while (TRUE)
{
$reg = '/([[:punct:]]+|[[:digit:]]+|[[:upper:]]+|[[:lower:]]+)/';
if (6 > preg_match_all($reg, $password, $arr))
break;
$c = 0;
$ps = array('punct', 'digit', 'upper', 'lower');
foreach ($ps as $pt)
{
if (preg_match("/[[:$pt:]]+/", $password))
$c += 1;
}
if ($c < 3) break;
if ("42" == $password) echo $flag;
else echo 'Wrong password';
exit;
}
}
//https://segmentfault.com/q/1010000012046306
$red_money = 143.66;
$receive_money = 14.55;
$residue_money = $red_money > $receive_money ? $red_money - $receive_money : 0;
$receive_money = $residue_money * 100;
var_dump($receive_money);//12911
var_dump((int)$receive_money);/12910
var_dump(intval(12910.9));//int(12910)
var_dump($receive_money*10000);//12910000
var_dump((int)($receive_money*10000));//12910999
var_dump(decbin($receive_money));
var_dump(decbin(12911));</code></pre>
<p>ps: php 7 优化和不兼容</p>
<pre><code class="js">$goo = [
"bar" => [
"baz" => 100,
"cug" => 900
]
];
$foo = "goo";
$$foo["bar"]["baz"]; // 实际为:($$foo)['bar']['baz']; PHP 5 中为:${$foo['bar']['baz']};https://zhuanlan.zhihu.com/p/29478077 https://github.com/justcodingnobb/fuck-php-interview https://github.com/todayqq/caseInterviewQuestions
$fn = function (?int $in) {
return $in ?? "NULL";
};
$fn(null);
$fn(5);
$fn(); // TypeError: Too few arguments to function {closure}()</code></pre>
<p><img src="/img/bVTf8h?w=1926&h=1354" alt="clipboard.png" title="clipboard.png"></p>
<h3><a href="https://link.segmentfault.com/?enc=M%2F6LlqSG1Dy8lx%2BDMtCsEQ%3D%3D.AjWMbW9O6Nd%2BMrM1DDyYamfJPZ13yHbAf3eCfa4KJcilKG01AtdCsqywKQfoC4ZV" rel="nofollow">PDO bindParam 要求第二个参数是一个引用变量</a></h3>
<pre><code class="js">$dbh = new PDO('mysql:host=localhost;dbname=test', "test");
$query = <<<QUERY
INSERT INTO `user` (`username`, `password`) VALUES (:username, :password);
QUERY;
$statement = $dbh->prepare($query);
$bind_params = array(':username' => "laruence", ':password' => "weibo");
foreach( $bind_params as $key => $value ){
$statement->bindParam($key, $value);
}
$statement->execute();
//期望执行 sql
INSERT INTO `user` (`username`, `password`) VALUES ("laruence", "weibo");
// 实际执行 sql
INSERT INTO `user` (`username`, `password`) VALUES ("weibo", "weibo");
//第一次循环
$value = $bind_params[":username"];
$statement->bindParam(":username", &$value); //此时, :username是对$value变量的引用
//第二次循环
$value = $bind_params[":password"]; //oops! $value被覆盖成了:password的值
$statement->bindParam(":password", &$value);
// 解决
foreach( $bind_params as $key => &$value ) { //注意这里
$statement->bindParam($key, $value);
}
return $statement->execute($params);</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=8qz0%2BfRZ1R8TQcA14s9D9w%3D%3D.zwNtAN6kFm3qeqmM%2BZzN4RadOS4Mi0OdvYjz8aKvN8KHrkWP0cXlgvFQgFgoK64D" rel="nofollow">PHP 引用</a></h3>
<p>参考鸟哥一条微博<br><img src="/img/bVTf6O?w=540&h=554" alt="clipboard.png" title="clipboard.png"></p>
<pre><code class="js"> $arr = range(1,3);
foreach($arr as &$v){
}
foreach($arr as $v){
}
print_r($arr);//[1,2,2]
// 解决一
$arr = range(1,3);
foreach($arr as &$v){
}
unset($v);
foreach($arr as $v){
}
print_r($arr);//[1,2,3]
// 解决二
$arr = range(1,3);
foreach($arr as &$v){
}
foreach($arr as $v2){
}
print_r($arr);//[1,2,3]
// 解决三
$arr = range(1,3);
foreach($arr as &$v){
}
foreach($arr as &$v){
}
print_r($arr);//[1,2,3]</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=u2sacYvMCD8iclSBEjHJnw%3D%3D.p1%2FWknEu6QwszDuUziWbp%2BhwIizQ4T15WElEhLzoG%2BkoMhSTp1TpdRUxAcLZAI15" rel="nofollow">array_merge vs +</a></h3>
<pre><code class="js">//
$arr1 = array(1 => "one", "2" => "two", 3 => "three");
$arr2 = array(2 => "new two", 3 => "new three");
print_r($arr1 + $arr2);
Array
(
[1] => one
[2] => two
[3] => three
)
print_r(array_merge($arr1, $arr2));
Array
(
[0] => one
[1] => two
[2] => three
[3] => new two
[4] => new three
)</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=La8nXR7EJG9i6NNFb3uxUw%3D%3D.1ajA5gJO2nO7XqViSe2Leo%2ByqkJbhPEM6I9qfXb%2FLNT85jWclIZGQyubJ8tX93nmv2j0pVC%2BbMgcmSzV76NNGw%3D%3D" rel="nofollow">浮点数精度问题</a></h3>
<p><img src="/img/bVTgeP?w=472&h=132" alt="clipboard.png" title="clipboard.png"></p>
<pre><code class="js">
var_dump(15702>=(157.02*100));//bool(false)
var_dump(11111>=(111.11*100));//bool(true)
var_dump(bcsub(15702,(157.02*100)) >= 0);//bool(true)
if(abs(15702-(157.02*100)) < 0.001) {
echo "相等";
} else {
echo "不相等";
}
$f = 0.58;
var_dump(intval($f * 100)); //57 0.58 * 100 = 57.999999999...</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=EtQeXvx6lFDno4VrsJz0cg%3D%3D.VwUIStMGU2djaa77jtfjK0h%2FuFuo4jOC%2FhH9tAtMkv%2BZ5hStcOA8gFOmlrbcLqs%2F" rel="nofollow">in_array switch/case 松散比较</a></h3>
<pre><code class="js"> $arr = ['a', 'pro' => 'php', 8, true];
var_dump(in_array(2, $arr)); // bool(true)
var_dump(in_array('b', $arr)); // bool(true)
var_dump(in_array(0, $arr)); // tbool(true)
var_dump(in_array(null, $arr)); // bool(false)
var_dump(in_array(2, $arr, true)); // bool(false)
var_dump(in_array(0, $arr, true)); // bool(false)
$name = 0;
switch ($name) {
case "a":
//...
break;
case "b":
//...
break;
}
switch (strval($name)) {
case "a":
//...
break;
case "b":
//...
break;
}
//http://php.net/manual/zh/types.comparisons.php#types.comparisions-loose
function test($var)
{
switch (true)
{
case 'apple' === $var:
echo 'apple', PHP_EOL;
break;
case 0 === $var:
echo '0', PHP_EOL;
break;
default:
echo 'default', PHP_EOL;
}
}
$arr = array('0', 0, 'apple');
foreach ($arr as $value)
{
test($value);
} </code></pre>
<h3><a href="https://link.segmentfault.com/?enc=grQ%2F1QXa8HjEoeQ%2FKO8nQQ%3D%3D.Z1WxkBE596VcWi9%2BOEy5P%2BqBQhY%2F%2ByWEzopSGsTj5mfwjaCas%2BxJmtXmRPKxbCGJ" rel="nofollow">strpos</a></h3>
<pre><code class="js">function getReferer($link)
{
$refMap = [
'baidu' => '百度',
'sougou' => '搜狗',
'360' => '360',
'google' => '谷歌'
];
foreach ($refMap as $key => $value) {
if (strpos($link, $key) !== false) {
return $value;
}
}
return '其他';
}
// https://secure.php.net/manual/zh/function.strpos.php 如果 needle 不是一个字符串,那么它将被转换为整型并被视为字符的顺序值。
echo getReferer('https://www.google.com/search?workd=google');//360
// 解决
function getReferer($link)
{
$refMap = [
'baidu' => '百度',
'sougou' => '搜狗',
'360' => '360',
'google' => '谷歌'
];
foreach ($refMap as $key => $value) {
if (mb_strpos($link, $key) !== false) {
//if (strpos($link, strval($key)) !== false) {
return $value;
}
}
return '其他';
}</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=jaILrx4UvSF%2BCOzY54j%2BHg%3D%3D.F5G7YHMeRzKdDOSzMlG3wmQI3e7JZ%2FWnZ4mIenwdv7v4%2F%2FMD8gYUU12mvZ5h1EGL" rel="nofollow">PHP 不同版本 curl 文件上传</a></h3>
<pre><code class="js">//PHP的cURL支持通过给CURL_POSTFIELDS传递关联数组(而不是字符串)来生成multipart/form-data的POST请求 https://blog.zsxsoft.com/post/5
if (class_exists('\CURLFile')) {
$field = array('fieldname' => new \CURLFile(realpath($filepath)));
} else {
$field = array('fieldname' => '@' . realpath($filepath));
}</code></pre>
<h3>foreach 顺序</h3>
<pre><code class="js">$arr=[];
$arr[2] = 2;
$arr[1] = 1;
$arr[0] = 0;
foreach ($arr as $key => $val) {
echo $val;// 2 1 0
}
while (list($key, $v) = each($arr)) {
//获取不到 foreach会自动reset,each之前, 先reset数组的内部指针
}
for($i=0,$l=count($arr); $i<$l; $i++) {
echo $arr[$i];// 0 1 2
}</code></pre>
<h3>json_decode</h3>
<pre><code class="js">>>> json_decode('php')
=> null
// 对非 json 字符串并非返回 null
>>> json_decode('0x123')
=> 291
echo json_encode(["name" => "php", "age" => "22"]) . "\n";// {"name":"php","age":"22"}
echo json_encode([]) . "\n";//[] 返回这个会让 APP 崩溃
echo json_encode((object)[]) . "\n";//{}
>>> $a = 0.1 + 0.7
=> 0.8
>>> printf('%.20f', $a)
=> 0.79999999999999993339
>>> json_encode($a)
=> "0.7999999999999999"
>>> \YaJson::encode($a)//https://github.com/seekerliu/laravel-another-json
=> "0.8"
ini_set('serialize_precision', 14);
$a = 0.1 + 0.7;
echo json_encode($a);//0.8
echo json_decode(0.7999999999999999);//0.8</code></pre>
<h3>strtotime('-x month')</h3>
<pre><code class="js">date_default_timezone_set('Asia/Shanghai');
$t = strtotime('2017-08-31');
echo date('Ym',strtotime('- 1 month',$t));//201707
echo date('Ym',strtotime('- 2 month',$t));//201707 ?
//
$first_day_of_month = date('Y-m',strtotime('2017-08-31')) . '-01 00:00:01';
$t = strtotime($first_day_of_month);
echo date('Ym',strtotime('- 1 month',$t));//201707
echo date('Ym',strtotime('- 2 month',$t));//201706
echo date("Ym", strtotime("-2 month", strtotime("first day of 2017-08-31")));//201706</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=kqVYRCqWEdASO0NFYQM0Fg%3D%3D.WFp6eYqZCPEvXUx%2FD7mJLPa67cGnc5Tl5U4IHFaWH8BIAmJQXM60qbqrGE98lmCAj23aVxerpph%2Byfb54q19PDTKYtuCDFnjne%2Fl9hMaCsk%3D" rel="nofollow">BOM</a></h3>
<pre><code class="js">//json 解析成 null 写代码时指定 utf-8 without bom
function remove_utf8_bom($text)
{
$bom = pack('H*','EFBBBF');
$text = preg_replace("/^$bom/", '', $text);
return $text;
}
// ps:PHP导出Excel 可能会乱码,需要写入 BOM头
$content = pack('H*','EFBBBF');
fwrite($fp, $content);</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=57gSXd4g2subuRc3R%2FvEmw%3D%3D.NKhu6dflkwXrDLviAiFkbOYTQRSAupJaT55SkgOynG65kwnIkRUVf%2FyXCicNRMiUpN%2BJC8DmHWR99JI2jY1Sw%2Bk6AizQuWiU8e4Yhzq%2FK2Y%3D" rel="nofollow">PHP解析大整数</a></h3>
<pre><code class="js">$shopId = 17978812896666957068;
var_dump($shopId);//float(1.7978812896667E+19)
$shopId= number_format(17978812896666957068);
var_dump($shopId);//17978812896666957824
$shopId= strval(17978812896666957068);
var_dump($shopId);
$shopId = 17978812896666957068 . '';
var_dump($shopId);//float(1.7978812896667E+19)
$shopId = '17978812896666957068';
var_dump($shopId);
// 输出
// string(20) "17978812896666957068"
超过PHP最大表示范围的纯整数,在MySQL中可以使用bigint/varchar保存,MySQL在查询出来的时候会将其使用string类型保存的。 对于赋值,在PHP里,如果遇到有大整数需要赋值的话,不要尝试用整型类型去赋值$var = '17978812896666957068';
#</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=tuOj4CrESVFGBpUKynZxdQ%3D%3D.t7f%2FKBMRL1gTRXV2am5Nk9g8xq6EmWfeWps%2BBVp4d34dHO%2FpvxINTT8jntzIj9A09T8Ui04Zrg0Dq211uPPeAA%3D%3D" rel="nofollow"> curl获取网页内容出现乱码</a></h3>
<pre><code class="js">curl_setopt($ch,CURLOPT_ENCODING,'gzip')//)如果抓取的网页进行了gzip压缩 加入gzip解析
$data = file_get_contents("compress.zlib://".$url); // Header 里 Accept-Encoding:gzip 是告诉对方服务器使用 Gzip 进行传输。 </code></pre>
<h3><a href="https://link.segmentfault.com/?enc=AMul6BMutDesUsa1Zq1abg%3D%3D.AfFpMwYjBWRjiKrIWRoM78Fo0oJfUVqpFZckXtzbnlU%3D" rel="nofollow">trim 中文乱码</a></h3>
<pre><code class="js">
echo rawurlencode('河北省');//%E6%B2%B3%E5%8C%97%E7%9C%81
echo rawurlencode('广东省');//%E5%B9%BF%E4%B8%9C%E7%9C%81
echo rtrim('河北省', '省');//河北
echo rtrim('广东省', '省');//广��
//省的十六制作表示是e7 9c 81,而东的十六进制表示是e4 b8 9c,都出现了9c,哦~正因为是rtrim,所以rtrim('广东省', '省')的时候把“东”的十六进制表示的最后一位也被trim掉了。同理rtrim('河北省', '省')不存在此问题
echo trim_cn('广东省','省');//广东
function trim_cn($str, $trim, $charset = 'UTF-8') {
$len = mb_strlen($str, $charset);
if (!$len)
return;
$t1 = $t2 = false;$o=$l=0;
for($i=0;$i<$len;$i++)
{
$str1 = mb_substr($str, $i, 1, $charset);
$str2 = mb_substr($str, $len-$i-1, 1, $charset);
if($str1 == $trim && !$t1) $o++; else $t1 = true;
if($str2 == $trim && !$t2) $l++; else $t2 = true;
}
return mb_substr($str, $o, ($len-$l-$o), $charset);;
}</code></pre>
<h3>__callStatic</h3>
<pre><code class="js">//在对象中调用一个不可访问方法时,__call() 会被调用
//在静态上下文中调用一个不可访问方法时,__callStatic() 会被调用 目标方法非 public 时__callStatic 才会起作用。
class A{
public static function __callStatic($name, $arguments)
{
echo $name.'静态方法不存在!';
}
public function test()
{
echo 'test 方法';
}
}
A::test();//test 方法
</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=zNEMMTR8nhRncIGUNKEorQ%3D%3D.zROoWZH99taEimKAj0Inl9scph9cIi48OA%2BTlZfXq9w%3D" rel="nofollow">mb_substr字符编码</a></h3>
<pre><code class="js">$str = '北京市朝阳区';
var_dump(mb_substr($str,0,3));//预期输出是:string(9) "北京市",但是输出确是:string(3) "北"
//mb_substr这个函数在操作的时候如果没有传字符编码,则按照默认的内部编码操作字符串。PHP5.6之前的默认编码都是ISO-8859-1,5.6之后的才是UTF8,UTF8模式下,一个中文字符占3个字节,而ISO-8859-1则是按照一个字节进行处理,所以自然取出来的是异常的字符串。
var_dump(mb_substr($str,0,3,'UTF-8'));//string(9) "北京市"</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=eJWG7Vvcrbu%2FfbByZdxkmA%3D%3D.dez%2BvqdG9DjUPXZ0MBMxru8LwS%2Fe6OElWdfU5%2FaQSiQuxknjVBYCwVZpB44ZAhbp" rel="nofollow">url参数中的+替换为空格</a></h3>
<pre><code class="js">$name=str_replace('%20','+',$_GET['name']);
//安全 base64
function urlsafeB64Decode($input)
{
$remainder = strlen($input) % 4;
if ($remainder) {
$padlen = 4 - $remainder;
$input .= str_repeat('=', $padlen);
}
return base64_decode(strtr($input, '-_', '+/'));
}
function urlsafeB64Encode($input)
{
return str_replace('=', '', strtr(base64_encode($input), '+/', '-_'));
}</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=KMm6fW%2F8Orhw1WVRh9uXVg%3D%3D.JozoBeR9sA4t6hGYaAojGEy21M3lcoXvovpY0X%2B88AcAEH%2Bliq0SwqMd8Av5cvsg" rel="nofollow">array Undefined offset</a></h3>
<pre><code class="js"># php -a
php > $a=[];
php > echo $a[1];
PHP Notice: Undefined offset: 1 in php shell code on line 1
php > $a=null;
php > echo $a[1];
php > $a=4;
php > echo $a[1];</code></pre>
<h3>数组比较</h3>
<pre><code class="js">array("foo", "bar") != array("bar", "foo"); //这个时候,array就是数组
array("foo" => 1, "bar" => 2) == array("bar" => 2, "foo" => 1); //这个时候,array又变成了无序hash表
$first = array("foo" => 123, "bar" => 456);
$second = array("foo" => 456, "bar" => 123);
var_dump(array_diff($first, $second));
==> array()</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=zuwKOk0RkCLAY9twHLE7AA%3D%3D.UDZXV56hLpFh7g0mhS3tsCamceChUXCYfJn0Hc9PEoSE%2BPg%2F8xNca5Y2qzHFOxR4MkkCdDeu8R5AEckeYhUcLg%3D%3D" rel="nofollow">数组序列化</a></h3>
<pre><code class="js">$arrA = array('a', 'b', 'c');
echo json_encode($arrA) . "\n";
$arrB = array('a' => 1, 'b' => 2, 'c' => 3);
echo json_encode($arrB) . "\n";
["a","b","c"]
{"a":1,"b":2,"c":3}
$arrA = array(1 => 'a', 2 => 'b', 3 => 'c');
echo json_encode($arrA) . "\n";
$arrA = array(0 => 'a', 2 => 'b', 3 => 'c');
echo json_encode($arrA) . "\n";
{"1":"a","2":"b","3":"c"}
{"0":"a","2":"b","3":"c"}
//仅当数组的key是从0开始的整数,并且key连续不间断,对其序列化的结果才是JS中的数组,也就是通常认为的PHP索引数组。</code></pre>
<h3>json 解析错误</h3>
<pre><code class="js">删除控制符
function strip_control_characters($str){
return preg_replace('/[\x00-\x1F\x7F-\x9F]/u', '', $str);
}
删除BOM解决:sed -i '1 s/^\xef\xbb\xbf//' file</code></pre>
<h3>32位系统2038年问题</h3>
<pre><code class="js">1、日期字符串转换为时间戳
$obj = new DateTime("2050-12-31 23:59:59");
echo $obj->format("U"); // 2556115199
// 2、时间戳转换为日期字符串
$obj = new DateTime("@2556115199"); // 这里时间戳前要写一个@符号
$timezone = timezone_open('Asia/HONG_KONG'); // 设置时区
$obj->setTimezone($timezone);
echo $obj->format("Y-m-d H:i:s"); // 2050-12-31 23:59:59
// 而且DateTime还可以有其他玩法
$obj = new DateTime("2050-12-31 23:59:59");
echo $obj->format("Y/m/d H:i:s"); // 换种方式输入时间字符串2050/12/31 23:59:59
var_dump(strtotime("2050-12-31 23:59:59"));//false</code></pre>
<p>更多<br><a href="https://segmentfault.com/a/1190000011328199">浮点数那些事儿</a><br><a href="https://link.segmentfault.com/?enc=V4Ub%2Bt3sLFccqOLpTWhxvw%3D%3D.R%2BWrp6tUAqOjshFsUN16V7kN%2FHdRhoWSgd95b6i9vTRMXlUs0h%2BcmmlLm697SugbuqGTcecJnB%2FHjU%2FXFcFedj2mAetNhy0%2Bc7hYeiQPg9U%3D" rel="nofollow">https://eev.ee/blog/2012/04/0...</a><br><a href="https://link.segmentfault.com/?enc=YV3M%2Bj97FSA5IT8ns30OOA%3D%3D.yb%2F2RPgi8QTYLR%2Foqc%2Fi5W%2BZ5zufDLEMhKXRKkOMuJS7%2Fc8Jw3a47tBjMlE%2FxN%2FwbQclO1jJao%2FK2afkdWK34uL8HKViMkbrfjYNQDpA4K0%3D" rel="nofollow">http://bayescafe.com/php/the-...</a><br><a href="https://link.segmentfault.com/?enc=JZcG5UoeNri8nzMgstSQZA%3D%3D.WAsPlwkP0sHVqQbNXyd0bbc83b5XgjwU17i0OOIu7WVwAGV%2FP2oebagTZdmv%2Fkma" rel="nofollow">http://bayescafe.com/php/yueb...</a><br><a href="https://link.segmentfault.com/?enc=Ro0N%2Fii7MIgMFjqbytcXGQ%3D%3D.89SYjsSyTZs1kMa6DBkemk5PMUr66tj6oQ3a9tTWaE4%3D" rel="nofollow">https://www.unphp.net/api/</a><br><a href="https://link.segmentfault.com/?enc=qlLXwdZGelRs6z1MOZPVwg%3D%3D.6bP%2F7zmQqsL73AGgBdfnr9Je9NcHVAPGZ5pkFxQuQhYXfYkBHKz19buzuTNc8NPD" rel="nofollow">https://blog.zsxsoft.com/post/30</a><br><a href="https://link.segmentfault.com/?enc=PJsZj4I6AGok7OfWN0b3Dw%3D%3D.D4jF%2FQBqGVSou3ByBNk5B%2BcgF7%2B2nDhzWtI9wzBIlwM%3D" rel="nofollow">http://coffeephp.com/articles/4</a><br><a href="https://link.segmentfault.com/?enc=AzkG9L1on9XVuKGd1nq85A%3D%3D.QKV5jr0PTTGHWLb%2Fp9qCthzdXmV4xUAKW53bzrOvcfsBnPkyMRbaGecNAw71dF5S93290fEDtJKf3MSYDVDgdm5tYf%2F4cLHfc44g5tzWfNo%3D" rel="nofollow">http://me.veekun.com/blog/201...</a><br><a href="https://link.segmentfault.com/?enc=HOVjIFsR2i9ZXjz%2F7K06%2Bw%3D%3D.20IswuSKYPMbLzd7n2JWdMPal7O07M%2BDDQEU46t%2FwTqcrZqr%2BqVg6yP5HPlenQr%2BMNfJ5ZJKF3P%2FtIMVO%2Bb5rdOXTmGBecwTbfcUdmXCA14%3D" rel="nofollow">https://jingxin.me/blog/blog/...</a><br><a href="https://link.segmentfault.com/?enc=QtqvIjh2yZPWxlf2NLeIgw%3D%3D.R8yAtB3W7wUIbICvd0Ur2%2FnQe6%2BB%2BJsyQ7l63SoMB2f%2BYpyIH%2FbdSxnYJJ6SYnOw" rel="nofollow">https://juejin.im/post/5a3332...</a> <br><a href="https://link.segmentfault.com/?enc=0JqNjHK3VkTD9pJS0Y5I5w%3D%3D.DReXHNbBXwpDZ3rCE%2FSbhiyw%2BksZWGxchS4qITXP7ySeZCNeiqH9c6IacRKt2FUfKxy%2BoSTKNqaz6nx1Nlw2fg%3D%3D" rel="nofollow">https://mp.weixin.qq.com/s/xw...</a> <br>十个 PHP 开发者最容易犯的错误 <a href="https://segmentfault.com/a/1190000014126990">https://segmentfault.com/a/11...</a><br>PHP弱类型引发的漏洞实例 <a href="https://link.segmentfault.com/?enc=zjaAWNOaPnHPr8odrYvtDQ%3D%3D.THL19WYFpyttvTkecb91dYY4%2Fx32tXby3FUOJczdIZDfhvNkE6%2FtkdRCwA%2FTg37m" rel="nofollow">http://www.freebuf.com/articl...</a></p>
php 获取 ip 信息
https://segmentfault.com/a/1190000010406804
2017-07-29T12:24:28+08:00
2017-07-29T12:24:28+08:00
苏生不惑
https://segmentfault.com/u/sushengbuhuo
4
<p>PHP 获取 ip 地址信息之前用过新浪/淘宝的接口,但如果新浪/淘宝接口出问题就没法用了,而且网络获取也慢.<br>今天介绍一个开源的<a href="https://link.segmentfault.com/?enc=BnnY4XHPjs8hlt6PvDw1CQ%3D%3D.87JLthwCyb8YNxkml2OVXchGht059%2FQKhjPEZzp1BE7vtFhZvvJ%2BwiVbk8Sq7pRj" rel="nofollow">geoip</a></p>
<h3>淘宝接口</h3>
<pre><code class="js">$ip = file_get_contents('http://ip.taobao.com/service/getIpInfo.php?ip=180.149.132.47');
print_r(json_decode($ip, 1));
Array
(
[code] => 0
[data] => Array
(
[country] => 中国
[country_id] => CN
[area] => 华北
[area_id] => 100000
[region] => 北京市
[region_id] => 110000
[city] => 北京市
[city_id] => 110100
[county] =>
[county_id] => -1
[isp] => 电信
[isp_id] => 100017
[ip] => 180.149.132.47
)
)</code></pre>
<h3>纯真 IP 数据库</h3>
<pre><code class="js">// 先下文件 QQWry.Dat http://www.cz88.net/fox/ http://update.cz88.net/soft/setup.zip
$IpLocation = new IpLocation('qqwry/QQWry.Dat');
$client = $IpLocation->getlocation('180.149.132.47');</code></pre>
<h3>安装 geoip</h3>
<pre><code class="js">curl -sS https://getcomposer.org/installer | php
mv composer.phar /usr/bin/composer
chmod +x composer
composer require geoip2/geoip2:~2.0
</code></pre>
<h3>使用</h3>
<pre><code class="js">require_once 'vendor/autoload.php';
use GeoIp2\Database\Reader;
$reader = new Reader('GeoIP2-City.mmdb');
$record = $reader->city('180.149.132.47');// 百度 ip
dump($record);// dump 来自 laravel
City {#1899 ▼
#city: City {#1908 ▶}
#location: Location {#1909 ▶}
#postal: Postal {#1910 ▶}
#subdivisions: array:1 [▶]
#continent: Continent {#1902 ▶}
#country: Country {#1903 ▶}
#locales: array:1 [▶]
#maxmind: MaxMind {#1904 ▶}
#registeredCountry: Country {#1905 ▶}
#representedCountry: RepresentedCountry {#1906 ▶}
#traits: Traits {#1907 ▶}
#raw: array:7 [▼
"city" => array:2 [▼
"geoname_id" => 1816670
"names" => array:8 [▼
"de" => "Peking"
"en" => "Beijing"
"es" => "Pekín"
"fr" => "Pékin"
"ja" => "北京市"
"pt-BR" => "Pequim"
"ru" => "Пекин"
"zh-CN" => "北京"
]
]
"continent" => array:3 [▼
"code" => "AS"
"geoname_id" => 6255147
"names" => array:8 [▼
"de" => "Asien"
"en" => "Asia"
"es" => "Asia"
"fr" => "Asie"
"ja" => "アジア"
"pt-BR" => "Ásia"
"ru" => "Азия"
"zh-CN" => "亚洲"
]
]
"country" => array:3 [▼
"geoname_id" => 1814991
"iso_code" => "CN"
"names" => array:8 [▼
"de" => "China"
"en" => "China"
"es" => "China"
"fr" => "Chine"
"ja" => "中国"
"pt-BR" => "China"
"ru" => "Китай"
"zh-CN" => "中国"
]
]
"location" => array:4 [▼
"accuracy_radius" => 50
"latitude" => 39.9289
"longitude" => 116.3883
"time_zone" => "Asia/Shanghai"
]
"registered_country" => array:3 [▼
"geoname_id" => 1814991
"iso_code" => "CN"
"names" => array:8 [▼
"de" => "China"
"en" => "China"
"es" => "China"
"fr" => "Chine"
"ja" => "中国"
"pt-BR" => "China"
"ru" => "Китай"
"zh-CN" => "中国"
]
]
"subdivisions" => array:1 [▼
0 => array:3 [▼
"geoname_id" => 2038349
"iso_code" => "11"
"names" => array:3 [▼
"en" => "Beijing"
"fr" => "Municipalité de Pékin"
"zh-CN" => "北京市"
]
]
]
"traits" => array:1 [▼
"ip_address" => "180.149.132.47"
]
]
}
print($record->country->isoCode . "\n"); // 'CN'
print($record->country->name . "\n"); // 'China'
print($record->country->names['zh-CN'] . "\n"); // '中国 '
print($record->mostSpecificSubdivision->name . "\n"); // 'Beijing'
print($record->mostSpecificSubdivision->isoCode . "\n"); // '11'
print($record->city->name . "\n"); // 'Beijing '
print($record->location->latitude . "\n"); // 39.9289
print($record->location->longitude . "\n"); // 116.3883</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=%2BhYzO7nqhqR0E90P2%2BUiFQ%3D%3D.w7etAKApNChb%2BmAswyYrkPfIvk99ojpqn94qxm8iai3rlEjMT0tS8VXFSIwMkUdG" rel="nofollow">ip2region</a></h3>
<pre><code class="js">php binding/php/testSearcher ./data/ip2region.db
p2region>> 101.105.35.57
2163|中国|华南|广东省|深圳市|鹏博士 in 0.02295 millseconds</code></pre>
<p>公众号:苏生不惑</p>
<p><img src="/img/bVOYWr?w=425&h=433" alt="clipboard.png" title="clipboard.png"></p>
mysql 分组
https://segmentfault.com/a/1190000010406410
2017-07-29T11:34:23+08:00
2017-07-29T11:34:23+08:00
苏生不惑
https://segmentfault.com/u/sushengbuhuo
1
<h3>表结构和数据</h3>
<pre><code class="js">create table cat(
id(1) int not null auto_increment primary key,
cat_id int(1),
value int(1),
name varchar(20)
);
insert into cat (cat_id,name,value) values ('1','name1', '1');
insert into cat (cat_id,name,value) values ('1','name2', '2');
insert into cat (cat_id,name,value) values ('1','name3', '3');
insert into cat (cat_id,name,value) values ('1','name4', '4');
insert into cat (cat_id,name,value) values ('2','name5', '5');
insert into cat (cat_id,name,value) values ('2','name6', '6');
insert into cat (cat_id,name,value) values ('2','name7', '7');
insert into cat (cat_id,name,value) values ('2','name8', '8');
insert into cat (cat_id,name,value) values ('3','name9', '9');
insert into cat (cat_id,name,value) values ('3','name10','10');
insert into cat (cat_id,name,value) values ('3','name11','11');
insert into cat (cat_id,name,value) values ('3','name12','12');
mysql> select *from cat;
+----+--------+-------+--------+
| id | cat_id | value | name |
+----+--------+-------+--------+
| 1 | 1 | 1 | name1 |
| 2 | 1 | 2 | name2 |
| 3 | 1 | 3 | name3 |
| 4 | 1 | 4 | name4 |
| 5 | 2 | 5 | name5 |
| 6 | 2 | 6 | name6 |
| 7 | 2 | 7 | name7 |
| 8 | 2 | 8 | name8 |
| 9 | 3 | 9 | name9 |
| 10 | 3 | 10 | name10 |
| 11 | 3 | 11 | name11 |
| 12 | 3 | 12 | name12 |
+----+--------+-------+--------+
12 rows in set (0.13 sec) </code></pre>
<h3>查询分组最大记录</h3>
<pre><code class="js">// 默认取分组第一条
mysql> select *from cat group by cat_id order by cat_id;
+----+--------+-------+-------+
| id | cat_id | value | name |
+----+--------+-------+-------+
| 1 | 1 | 1 | name1 |
| 5 | 2 | 5 | name5 |
| 9 | 3 | 9 | name9 |
+----+--------+-------+-------+
3 rows in set (0.00 sec)
mysql> select *from (select *from cat order by value desc) a group by cat_id;
+----+--------+-------+--------+
| id | cat_id | value | name |
+----+--------+-------+--------+
| 4 | 1 | 4 | name4 |
| 8 | 2 | 8 | name8 |
| 12 | 3 | 12 | name12 |
+----+--------+-------+--------+
3 rows in set (0.06 sec)
mysql> select a.* from cat a where value = (select max(value) from cat where cat
_id = a.cat_id) order by a.cat_id;
mysql> select a.* from cat a,(select cat_id,max(value) value from cat group by cat_id) b where a.cat_id = b.cat_id and a.value = b.value order by a.cat_id;
mysql> select a.* from cat a inner join (select cat_id, max(value) value from cat group by cat_id) b on a.cat_id= b.cat_id and a.value= b.value order by a.cat_id;
+----+--------+-------+--------+
| id | cat_id | value | name |
+----+--------+-------+--------+
| 4 | 1 | 4 | name4 |
| 8 | 2 | 8 | name8 |
| 12 | 3 | 12 | name12 |
+----+--------+-------+--------+
3 rows in set (0.00 sec)
</code></pre>
<h3>分组前 3 条记录</h3>
<pre><code class="js">mysql> select a.* from cat a where exists (select count(*) from cat where cat_id= a.cat_id and value > a.value having Count(*) < 3) order by a.cat_id,a.value desc;
mysql> select *from cat a where (select count(*) from cat b where a.cat_id=b.cat_id and b.value>a.value) < 3 order by a.cat_id,a.value desc;
+----+--------+-------+--------+
| id | cat_id | value | name |
+----+--------+-------+--------+
| 4 | 1 | 4 | name4 |
| 3 | 1 | 3 | name3 |
| 2 | 1 | 2 | name2 |
| 8 | 2 | 8 | name8 |
| 7 | 2 | 7 | name7 |
| 6 | 2 | 6 | name6 |
| 12 | 3 | 12 | name12 |
| 11 | 3 | 11 | name11 |
| 10 | 3 | 10 | name10 |
+----+--------+-------+--------+
9 rows in set (0.15 sec)
</code></pre>
那些 PHP 开发者可能用得上的工具
https://segmentfault.com/a/1190000010205836
2017-07-16T12:03:43+08:00
2017-07-16T12:03:43+08:00
苏生不惑
https://segmentfault.com/u/sushengbuhuo
63
<h3><a href="https://link.segmentfault.com/?enc=Y%2FrBEPz2urf6%2FmNS3RUFuQ%3D%3D.is9Pdno%2FyFsAE%2B%2BoppjrpgOF19ydcy1Ntx5DuA2nv1wWVK1L%2Fd5Horjs3wfXl2do" rel="nofollow">PHP 函数的 JavaScript 实现</a></h3>
<pre><code class="js">module.exports = function array_sum (array) { // eslint-disable-line camelcase
// discuss at: http://locutus.io/php/array_sum/
// original by: Kevin van Zonneveld (http://kvz.io)
// bugfixed by: Nate
// bugfixed by: Gilbert
// improved by: David Pilia (http://www.beteck.it/)
// improved by: Brett Zamir (http://brett-zamir.me)
// example 1: array_sum([4, 9, 182.6])
// returns 1: 195.6
// example 2: var $total = []
// example 2: var $index = 0.1
// example 2: for (var $y = 0; $y < 12; $y++){ $total[$y] = $y + $index }
// example 2: array_sum($total)
// returns 2: 67.2
var key
var sum = 0
// input sanitation
if (typeof array !== 'object') {
return null
}
for (key in array) {
if (!isNaN(parseFloat(array[key]))) {
sum += parseFloat(array[key])
}
}
return sum
}</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=aUPN2HvioRPZK2CaabtMdQ%3D%3D.x92ltx%2BJf3uXscZX1%2FFz%2BsrwFV3EFzXvqkxEkYB55IAzk89Y9K9qQ78Cy%2BqbR2Ce" rel="nofollow">Underscore.js 的 PHP 版</a></h3>
<pre><code class="js">function __($item=null) {
$__ = new __;
if(func_num_args() > 0) $__->_wrapped = $item;
return $__;
}</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=cmqGsuv0uE7%2BTqbvK8DCMg%3D%3D.14rAsInNyHl482soiOCT1UUHupKjyPhlmftterCMcrI%3D" rel="nofollow">自动生成 gitignore 文件</a></h3>
<pre><code class="js">https://www.gitignore.io/api/laravel
# Created by https://www.gitignore.io/api/laravel
### Laravel ###
vendor/
node_modules/
npm-debug.log
# Laravel 4 specific
bootstrap/compiled.php
app/storage/
# Laravel 5 & Lumen specific
public/storage
public/hot
storage/*.key
.env.*.php
.env.php
.env
Homestead.yaml
Homestead.json
# Rocketeer PHP task runner and deployment package. https://github.com/rocketeers/rocketeer
.rocketeer/
# End of https://www.gitignore.io/api/laravel</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=K9lk%2FgpQ9YuVxMzTrIgnlQ%3D%3D.U%2Fqg4RyHFV310x22YN1yxxf%2BQus5ekX4JTEjFpW9BbwlW7RabFqdco%2B947STxeJk" rel="nofollow">爬虫组件</a></h3>
<pre><code class="js">composer global require slince/spider *@dev
use Slince\Spider\Spider;
$spider = new Spider();
$spider->run('http://www.baidu.com');</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=SEE42wdkvZmVyVkmavidFg%3D%3D.59J%2F1LF1VUybwKw8m5SNaChozb3YJyJXcURLs8TcmYY%3D" rel="nofollow">简单、 灵活、强大的 PHP 采集工具</a></h3>
<pre><code class="js">use QL\QueryList;
//采集某页面所有的图片
$data = QueryList::Query('http://cms.querylist.cc/bizhi/453.html',array(
//采集规则库
//'规则名' => array('jQuery选择器','要采集的属性'),
'image' => array('img','src')
))->data;
//打印结果
print_r($data);
//采集某页面所有的超链接
//可以先手动获取要采集的页面源码
$html = file_get_contents('http://cms.querylist.cc/google/list_1.html');
//然后可以把页面源码或者HTML片段传给QueryList
$data = QueryList::Query($html,array(
'link' => array('a','href')
))->data;
//打印结果
print_r($data);
在线测试采集并查看采集结果 http://querylist.cc/page-Querytest.html</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=eY49VNbUDenRZ5qUTrEMTw%3D%3D.kC0rjtYvvq7I%2BDdsNuWR0BPA4RLflU%2F2QgH4FwoeizZyIGG%2FUN2cEKlKb5P4jy9r" rel="nofollow">在线测试代码</a></h3>
<p><img src="/img/bVQY8N?w=929&h=565" alt="clipboard.png" title="clipboard.png"></p>
<pre><code class="js">$array=[
['name'=>'张三','age'=>'23'],
['name'=>'李四','age'=>'64'],
['name'=>'王五','age'=>'55'],
['name'=>'赵六','age'=>'66'],
['name'=>'孙七','age'=>'17'],
];
$sort = array(
'direction' => 'SORT_ASC', //排序顺序标志 SORT_DESC 降序;SORT_ASC 升序
'field' => 'age', //排序字段
);
$arrSort = array();
foreach($array as $uniqid => $row){
foreach($row AS $key=>$value){
$arrSort[$key][$uniqid] = $value;
}
}
array_multisort($arrSort[$sort['field']], constant($sort['direction']), $array);
print_r($array);</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=gsNAQ816lQC2E70ZmbExhw%3D%3D.fw4HxT96cKKTLwN41iPkEbYWKY%2B6RKoPnz%2BwHDd6%2BiNd7cKS8Mvj%2BhlFzaMKZ4Mw" rel="nofollow">中文转拼音工具</a></h3>
<pre><code class="js">//https://hellogithub.com/category/PHP%20%E9%A1%B9%E7%9B%AE/
use Overtrue\Pinyin\Pinyin;
$pinyin = new Pinyin();
$pinyin->convert('带着希望去旅行,比到达终点更美好');
// ["dai", "zhe", "xi", "wang", "qu", "lv", "xing", "bi", "dao", "da", "zhong", "dian", "geng", "mei", "hao"]
$pinyin->convert('带着希望去旅行,比到达终点更美好', PINYIN_UNICODE);
// ["dài","zhe","xī","wàng","qù","lǚ","xíng","bǐ","dào","dá","zhōng","diǎn","gèng","měi","hǎo"]
$pinyin->convert('带着希望去旅行,比到达终点更美好', PINYIN_ASCII);
//["dai4","zhe","xi1","wang4","qu4","lv3","xing2","bi3","dao4","da2","zhong1","dian3","geng4","mei3","hao3"]
</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=eCezbdvyfecERdlDLSZxAQ%3D%3D.vw%2FoPKDj6zV3WIZ4mTsmCQxEkgO8UIF5OKAOrCRWcWf6qrxON7uNqpQC6esU9ER0" rel="nofollow">美化 curl</a></h3>
<pre><code class="js">$ git clone https://github.com/talhasch/php-httpstat
$ cd php-httpstat
$ cp httpstat.php /usr/local/bin/httpstat
$ chmod +x /usr/local/bin/httpstat
$ httpstat http://www.google.com</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=9tinQz9X3fxohpYtHF1Iog%3D%3D.VsfkuOvdaKw%2BDAs4lOaNSGpFIp0BiKa47S8aA2qTajkiX%2FO%2FIqRq32q3LJ9SmDij" rel="nofollow">在线正则表达式测试</a></h3>
<p><img src="/img/bVQY4o?w=1325&h=592" alt="clipboard.png" title="clipboard.png"></p>
<h3><a href="https://link.segmentfault.com/?enc=EzvBsuK17i%2F2lhmm9zNzGA%3D%3D.FOrYcDnw4XJdxLaGRnf7GGz9782lWqZna0vLffBGSsU%3D" rel="nofollow">在线测试 redis</a></h3>
<p><img src="/img/bVQY9b?w=1228&h=554" alt="clipboard.png" title="clipboard.png"></p>
<h3><a href="https://link.segmentfault.com/?enc=QgTE7iX8%2B633JAX2OI4sZQ%3D%3D.slAIWIqXLwzknMvOOxf52WvXRXM3AiBNLFHYHcbHmDE%3D" rel="nofollow">在线练习 git</a></h3>
<p><img src="/img/bVQyFW?w=1190&h=531" alt="clipboard.png" title="clipboard.png"></p>
<h3><a href="https://link.segmentfault.com/?enc=Sj2vPZEYSz%2FQB49kWz4N5g%3D%3D.f9qjYCkx0IGpdWuycJ8i9JCxOd1D7wIGV0PslpHFXnG52z5UdikJ2chU9iUBWfrs" rel="nofollow">检测 PHP 应用的代码复杂度</a></h3>
<pre><code class="js">composer global require 'phploc/phploc=*'
$ phploc src
phploc 4.0.0 by Sebastian Bergmann.
Directories 3
Files 10
Size
Lines of Code (LOC) 1882
Comment Lines of Code (CLOC) 255 (13.55%)
Non-Comment Lines of Code (NCLOC) 1627 (86.45%)
Logical Lines of Code (LLOC) 377 (20.03%)
Classes 351 (93.10%)
Average Class Length 35
Minimum Class Length 0
Maximum Class Length 172
Average Method Length 2
Minimum Method Length 1
Maximum Method Length 117
Functions 0 (0.00%)
Average Function Length 0
Not in classes or functions 26 (6.90%)</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=rvptAqJfQRwro8qXtzOsmw%3D%3D.MZmhM4kat%2FQNt9bIodcWKCs3CaQhW%2BCM%2BJ0vyUQ%2BkSYkc0ieyUFl8H3fCephYXiA" rel="nofollow">php http 请求工具</a></h3>
<pre><code class="js">$response = Zttp::withHeaders(['Fancy' => 'Pants'])->post($url, [
'foo' => 'bar',
'baz' => 'qux',
]);
$response->json();
// => [
// 'whatever' => 'was returned',
// ];</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=JZMXGV82I9jpoTaYX9GgSA%3D%3D.N2BlRPJjEUMeZCCuHN1lTA%3D%3D" rel="nofollow">任务管理</a></h3>
<pre><code class="js">composer global require consolidation/robo
class RoboFile {
/**
* Each public method is a command in runner
* parameters are arguments in console
*
* use './robo test' to run tests on a project
*/
function test($pathToSelenium = '~/selenium.jar')
{
// starts PHP server in background
$this->taskPhpServer(8000)
->background()
->dir('web')
->run();
// launches Selenium server
$this->taskExec('java -jar '.$pathToSelenium)
->background()
->run();
// runs PHPUnit tests
$this->taskPHPUnit()
->run();
}</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=Rysnor6k6Fscz7vGntem8w%3D%3D.prGRTLHTgiGReoEpBOhhZnG4VJNcLO6Ce6twQNYO%2F9g%3D" rel="nofollow">phpstorm 技巧</a></h3>
<p><img src="/img/bVRo9U?w=1213&h=480" alt="clipboard.png" title="clipboard.png"></p>
<h3><a href="https://link.segmentfault.com/?enc=TE5FprOsAMtJoMYjEU3XxQ%3D%3D.NYNLagq1C6NATjETgMNgOD9IICJohwoTLA8GcOxuVRbI1y1%2BrJIBBJyZEbx4w5WP" rel="nofollow">php ai</a></h3>
<pre><code class="js">composer require php-ai/php-ml
require_once 'vendor/autoload.php';
use Phpml\Classification\KNearestNeighbors;
$samples = [[1, 3], [1, 4], [2, 4], [3, 1], [4, 1], [4, 2]];
$labels = ['a', 'a', 'a', 'b', 'b', 'b'];
$classifier = new KNearestNeighbors();
$classifier->train($samples, $labels);
echo $classifier->predict([3, 2]);
// return 'b'</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=5JFTTWLUW9ZVgb52m4Epig%3D%3D.%2BJybHvPDh8JC1zDjNfSmgNKxR0I0sw2KAQ7NyRyqMeLfz1MZ%2BtZ0mTZFN2OexAL5" rel="nofollow">PHP driver for FFMpeg</a></h3>
<pre><code class="js">$ffmpeg = FFMpeg\FFMpeg::create();
$video = $ffmpeg->open('video.mpg');
$video
->filters()
->resize(new FFMpeg\Coordinate\Dimension(320, 240))
->synchronize();
$video
->frame(FFMpeg\Coordinate\TimeCode::fromSeconds(10))
->save('frame.jpg');
$video
->save(new FFMpeg\Format\Video\X264(), 'export-x264.mp4')
->save(new FFMpeg\Format\Video\WMV(), 'export-wmv.wmv')
->save(new FFMpeg\Format\Video\WebM(), 'export-webm.webm');</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=4yk74rDBzHAXJR4gJuG9bA%3D%3D.irNUoNu8QvQfqaQtCMm79PoAaxYRrgI9rvp%2F7K%2FHvpSTQvGUEG3srrALO%2Btk4lFz" rel="nofollow">编码格式化工具</a></h3>
<pre><code class="js">//http://cs.sensiolabs.org/ composer global require fabpot/php-cs-fixer
//wget http://get.sensiolabs.org/php-cs-fixer.phar -O php-cs-fixer
curl http://get.sensiolabs.org/php-cs-fixer.phar -o php-cs-fixer
sudo chmod a+x php-cs-fixer
sudo mv php-cs-fixer /usr/local/bin/php-cs-fixer
# 格式化目录 如果是当前目录的话可以省略目录
php-cs-fixer fix /path/to/dir
# 格式化文件
php-cs-fixer.phar fix /path/to/file
//cat foo.php | php-cs-fixer fix --diff -
#https://housanpai.com/articles/10</code></pre>
<h3><a>php medoo</a></h3>
<pre><code class="js">composer require catfan/Medoo
// 如果你通过 composer 安装, 只需在项目的开始部分加上此代码即可自动加载。
require 'vendor/autoload.php';
// 或者你是下载 medoo.php 并放置到项目目录中,require 即可。
require 'medoo.php';
$database = new medoo([
// 必须的
'database_type' => 'mysql',
'database_name' => 'name',
'server' => 'localhost',
'username' => 'your_username',
'password' => 'your_password',
'charset' => 'utf8',
// [可选]
'port' => 3306,
// [可选] 表名前缀
'prefix' => 'PREFIX_',
// [可选] 连接的驱动选项,请阅读 http://www.php.net/manual/en/pdo.setattribute.php
'option' => [
PDO::ATTR_CASE => PDO::CASE_NATURAL
]
]);
$database->insert("account", [
"user_name" => "foo",
"email" => "foo@bar.com"
]);</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=mlaGeb8bwapDNfBlMCmVqg%3D%3D.8gyqJ4whI2SxrgStp7l5kwyA9v3pgc%2BUZZwkvP6pJ6%2F09BOtHKOXqXFTsUJ2QLAD" rel="nofollow">在线文档分享工具</a></h3>
<p><code>composer create-project showdoc/showdoc</code></p>
<h3><a href="https://link.segmentfault.com/?enc=YA5Ul0h6YDU7U62GMTzcYQ%3D%3D.mMAZ8HgkWKVQhZ%2FmDFjXUXdWPKNMK8gkhmHq8gGAgB%2BLDo%2BJHGZp4A43UT6amWDW" rel="nofollow">php的ngrok客户端</a></h3>
<h3><a href="#">比对两个数据库的表结构,并自动修正</a></h3>
<pre><code class="js">git clone https://github.com/exinnet/mysqldiff.git
cd mysqldiff
vi config.php # config mysql connection info
php mysqldiff.php</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=pC1BAyGOw5xuGeF%2B11rzCQ%3D%3D.w0UFlWimUsOCUGGS18OyAQZ%2BWakr9%2F%2F7qVV7imz8cHkAzUqgq%2FxAcg2dET1bmsZs" rel="nofollow">cron</a></h3>
<p><code>file_get_contents('https://hchk.io/e9ad1415-566c-40c9-9c97-a298d727ab68');</code></p>
<h3><a href="https://link.segmentfault.com/?enc=0O2Pu3fb3ekrpQu6%2Fv07ew%3D%3D.ROqu%2FF%2BN7gnn8tU0%2B%2BWT0y63lvGlyZGPU3XcKYCxls4RhnqrO1FpCrlT1mUuivoN" rel="nofollow">语法检测</a></h3>
<pre><code class="js">composer require overtrue/phplint -vvv
use Overtrue\PHPLint\Linter;
$path = __DIR__ .'/app';
$exclude = ['vendor'];
$extensions = ['php'];
$linter = new Linter($path, $exclude, $extensions);
// get errors
$errors = $linter->lint();
//
// [
// '/path/to/foo.php' => [
// 'error' => "unexpected '$key' (T_VARIABLE)",
// 'line' => 168,
// 'file' => '/path/to/foo.php',
// ],
// '/path/to/bar.php' => [
// 'error' => "unexpected 'class' (T_CLASS), expecting ',' or ';'",
// 'line' => 28,
// 'file' => '/path/to/bar.php',
// ],
// ]</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=zso2rpau1UEMQsrL%2B0gN2w%3D%3D.OAjyQRajh%2BZdsWIbF%2BiUWlExPG%2B9NPro5FPvG0wVCkSRevhLdIN52wZ42QEM0%2Fb66yL6J6wLWElda7TwGMOotw%3D%3D" rel="nofollow">生成Material Design风格头像</a></h3>
<pre><code class="js">// composer
require(__DIR__ . "/vendor/autoload.php");
use Md\MDAvatars;
$Avatar = new MDAvatars('X', 512);
$Avatar->Output2Browser();
$Avatar->Save('./avatars/Avatar256.png', 256);</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=nOza31zd2ce0oFHvPTBHKQ%3D%3D.VNdUsdcUhEfrdlNDXSnPnCKNuHlIq%2BT7A%2B1NKGYyRzMjArdjTuz65IrYpWUht3VS" rel="nofollow">使用screw plus来保护php代码安全</a></h3>
<h3><a href="https://link.segmentfault.com/?enc=hCxkppmHuTvupV2F8TGJxA%3D%3D.GquqoSBqJYxjpJKa0b90P3tA3VDiFqPHj8F5OiJeeaPt%2FrOp468P80e%2Bv6AxPJr%2F" rel="nofollow">一个最精简的php多进程控制库</a></h3>
<pre><code class="js">$sf = new SimpleFork(2, 'my-process'); // 2代表子进程数, 'my-process'是进程的名字
$sf->master(function ($sf) {
// 主进程的方法请包裹在master里
while ($sf->loop(100)) { // 100为等待的毫秒数
$sf->submit('http://www.google.cn/', function ($data) { // 使用submit方法将其提交到一个空闲的进程,如果没有空闲的,系统会自动等待
echo $data;
});
}
})->slave(function ($url, $sf) {
$sf->log('fetch %s', $url); // 使用内置的log方法,子进程的log也会被打印到主进程里
return http_request($url); // 直接返回数据,主进程将在回调中收到
});</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=KcWaLczd%2BNtkK6wqtRok%2Bg%3D%3D.yY3uSm%2B9CpTHTLbxVE9BznIb%2FsRSHIu7uhnNJ7buqt29AhyRKyCteJNEPRDfTyN%2FD4kvYUtPhnhcqnM2NzHmtw%3D%3D" rel="nofollow">A PHP MySQL PDO class similar to the the Python MySQLdb</a></h3>
<pre><code class="js">$DB->query("SELECT * FROM fruit WHERE name=".$_GET['name']);
$DB->query("SELECT * FROM fruit WHERE name=? and color=?",array('apple','red'));
$DB->query("SELECT * FROM fruit WHERE name=:name and color=:color",array('name'=>'apple','color'=>'red'));
$DB->query("SELECT * FROM fruit WHERE name IN (?)",array('apple','banana'));
</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=VTHx0v4xB%2BIhss2y9NwVew%3D%3D.u8UmPuX45TYw6W6kW7Hpzn6wQA8yLp8RPNILjMCfXHNPfHOqls%2BE59mCzdrPeU19GmNlSTDdSbhJpawvgg6XRA%3D%3D" rel="nofollow">图片处理</a></h3>
<pre><code class="js">$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_URL, 'https://avatars0.githubusercontent.com/u/5785188?v=3&s=460');
$response = curl_exec($ch);
curl_close($ch);
$UploadAvatar = new ImageResize('String', $response);
$Result = $UploadAvatar->Resize(256, 'upload/avatar/large.png', 80);</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=eNN9qH98g3GNcIn4fqpzZw%3D%3D.7ypyfz%2FGtxK8APkQ8tAr5q0au9BA%2BktRN%2FOXCfBF0EVswqhvifGDjuO0xMXM7KDc" rel="nofollow"> Linux 图形化性能监视器</a></h3>
<h3><a href="https://link.segmentfault.com/?enc=w%2FGpJMiBYFFgDoWRYBwoDQ%3D%3D.MLUSV9iYa%2BR6p8w07greP00AqgFjN5U1L4%2BV%2F2MPTaU%3D" rel="nofollow">编写PHP代码片段终极机器人</a></h3>
<p><img src="/img/bVThAC?w=746&h=624" alt="clipboard.png" title="clipboard.png"></p>
<h3><a href="https://link.segmentfault.com/?enc=pRIlf6dOKxuoyWjIYKr%2FJQ%3D%3D.brT9BMVx9eQfM38wf%2B65dPOfnGUSILz%2BsutC36CVCKRpGDWyzzCpSqt%2BAE1JT753" rel="nofollow">PHP 代码转 Python</a></h3>
<pre><code class="js">def substr (self, s, start, length = None):
"""Returns the portion of string specified by the start and length
parameters.
"""
if len(s) >= start:
if start > 0:
return False
else:
return s[start:]
if not length:
return s[start:]
elif length > 0:
return s[start:start + length]
else:
return s[start:length]</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=j1rLNtNGunyJVoc7sxQv6A%3D%3D.Q7IiWuBMJWbSPjafnUXk6bRTIZ5rbqs9B%2BkUWbdvYPw%3D" rel="nofollow">php部署工具</a></h3>
<pre><code class="js">curl -LO https://deployer.org/deployer.phar
mv deployer.phar /usr/local/bin/dep
chmod +x /usr/local/bin/dep
composer require deployer/deployer</code></pre>
<p>公众号:苏生不惑</p>
<p><img src="/img/bVOYWr?w=425&h=433" alt="clipboard.png" title="clipboard.png"></p>
Python 词云分析周杰伦《晴天》
https://segmentfault.com/a/1190000010108177
2017-07-09T11:02:10+08:00
2017-07-09T11:02:10+08:00
苏生不惑
https://segmentfault.com/u/sushengbuhuo
2
<p>词云可以通过网站 <a href="https://link.segmentfault.com/?enc=goaEjZa6Zaw7FqHInl%2FpYQ%3D%3D.kjGX%2BFTiDYVg3mW%2BwQr75OQKeBYxSDcmN9iiKJJsidU%3D" rel="nofollow">https://wordart.com/</a> 纽扣词云<a href="https://link.segmentfault.com/?enc=Xibi%2BIMXhNA7JrU%2FV6kWWg%3D%3D.vwIUN%2FA19DzQbFBNWB8v1857PN9DMy40OPY7q3LUCCM%3D" rel="nofollow">http://cloud.niucodata.com/</a> 来制作,然而 Python 可以通过代码来实现,下面开始吧。</p>
<p><img src="/img/bVQzIx?w=874&h=416" alt="clipboard.png" title="clipboard.png"></p>
<pre><code class="js">pip install wordcloud ,jieba
import jieba,wordcloud
#选取周杰伦的《晴天》歌词
mytext = """
故事的小黄花
从出生那年就飘着
童年的荡秋千
随记忆一直晃到现在
ㄖㄨㄟ ㄙㄡ ㄙㄡ ㄒ一 ㄉㄡ ㄒ一ㄌㄚ
Re So So Si Do Si La
ㄙㄡ ㄌㄚ ㄒ一 ㄒ一 ㄒ一 ㄒ一 ㄌㄚ ㄒ一 ㄌㄚ ㄙㄡ
So La Si Si Si Si La Si La So
吹着前奏望着天空
我想起花瓣试着掉落
为你翘课的那一天
花落的那一天
教室的那一间
我怎么看不见
消失的下雨天
我好想再淋一遍
没想到失去的勇气我还留着
好想再问一遍
你会等待还是离开
刮风这天我试过握着你手
但偏偏雨渐渐大到我看你不见
还要多久我才能在你身边
等到放晴的那天也许我会比较好一点
从前从前有个人爱你很久
但偏偏风渐渐把距离吹得好远
好不容易又能再多爱一天
但故事的最后你好像还是说了拜拜
为你翘课的那一天
花落的那一天
教室的那一间
我怎么看不见
消失的下雨天
我好想再淋一遍
没想到失去的勇气我还留着
好想再问一遍
你会等待还是离开
刮风这天我试过握着你手
但偏偏雨渐渐大到我看你不见
还要多久我才能在你身边
等到放晴的那天也许我会比较好一点
从前从前有个人爱你很久
偏偏风渐渐把距离吹得好远
好不容易又能再多爱一天
但故事的最后你好像还是说了拜拜
刮风这天我试过握着你手
但偏偏雨渐渐大到我看你不见
还要多久我才能够在你身边
等到放晴那天也许我会比较好一点
从前从前有个人爱你很久
但偏偏雨渐渐把距离吹得好远
好不容易又能再多爱一天
但故事的最后你好像还是说了拜
"""
mytext = " ".join(jieba.cut(mytext))
from collections import Counter
c = Counter(text_jieba)
c = c.most_common(10)
[(' ', 522), ('\n', 98), ('你', 19), ('的', 17), ('我', 13), ('好', 10), ('但',
8), ('着', 8), ('再', 7), ('ㄒ', 7)]
from wordcloud import WordCloud
wordcloud = WordCloud(font_path="c:\windows\fonts\simhei.ttf").generate(mytext)
import matplotlib.pyplot as plt
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis("off")
plt.show()
# 保存图片
wordcloud.to_file('test.jpg')</code></pre>
<p><img src="/img/bVQzI3?w=498&h=253" alt="clipboard.png" title="clipboard.png"></p>
<p>下面进行歌词的情感分析</p>
<pre><code class="js">from snownlp import SnowNLP
s = SnowNLP(mytext)
for sentence in s.sentences:
print(sentence)
故事 的 小黄花
从 出生 那年 就 飘 着
童年 的 荡秋千
随 记忆 一直 晃到 现在
ㄖ ㄨ ㄟ ㄙ ㄡ ㄙ ㄡ ㄒ 一 ㄉ ㄡ ㄒ 一 ㄌ ㄚ
Re So So Si Do Si La
ㄙ ㄡ ㄌ ㄚ ㄒ 一 ㄒ 一 ㄒ 一 ㄒ 一 ㄌ ㄚ ㄒ 一 ㄌ ㄚ ㄙ ㄡ
So La Si Si Si Si La Si La So
吹 着 前奏 望 着 天空
我 想起 花瓣 试着 掉落
为 你 翘 课 的 那 一天
花落 的 那 一天
教室 的 那 一间
我 怎么 看不见
消失 的 下雨天
我 好 想 再 淋 一遍
没想到 失去 的 勇气 我 还 留 着
好 想 再 问 一遍
你 会 等待 还是 离开
刮风 这天 我试 过握 着 你 手
但 偏偏 雨 渐渐 大到 我 看 你 不见
还要 多久 我 才能 在 你 身边
等到 放晴 的 那天 也许 我会 比较 好 一点
从前 从前 有 个人 爱 你 很 久
但 偏偏 风 渐渐 把 距离 吹得 好 远
好不容易 又 能 再 多 爱 一天
但 故事 的 最后 你 好像 还是 说 了 拜拜
为 你 翘 课 的 那 一天
花落 的 那 一天
教室 的 那 一间
我 怎么 看不见
消失 的 下雨天
我 好 想 再 淋 一遍
没想到 失去 的 勇气 我 还 留 着
好 想 再 问 一遍
你 会 等待 还是 离开
刮风 这天 我试 过握 着 你 手
但 偏偏 雨 渐渐 大到 我 看 你 不见
还要 多久 我 才能 在 你 身边
等到 放晴 的 那天 也许 我会 比较 好 一点
从前 从前 有 个人 爱 你 很 久
偏偏 风 渐渐 把 距离 吹得 好 远
好不容易 又 能 再 多 爱 一天
但 故事 的 最后 你 好像 还是 说 了 拜拜
刮风 这天 我试 过握 着 你 手
但 偏偏 雨 渐渐 大到 我 看 你 不见
还要 多久 我 才 能够 在 你 身边
等到 放晴 那天 也许 我会 比较 好 一点
从前 从前 有 个人 爱 你 很 久
但 偏偏 雨 渐渐 把 距离 吹得 好 远
好不容易 又 能 再 多 爱 一天
但 故事 的 最后 你 好像 还是 说 了 拜
#第一句的情感分析结果
s1 = SnowNLP(s.sentences[0])
s1.sentiments
0.8849970682062196#正向情感
#分析 好不容易 又 能 再 多 爱 一天
s1 = SnowNLP(s.sentences[-2])
s1.sentiments
0.21646625648493734#这个情绪就比较负面了</code></pre>
<p>公众号:苏生不惑</p>
<p><img src="/img/bVOYWr?w=425&h=433" alt="clipboard.png" title="clipboard.png"></p>
那些有趣/用的 Python 库
https://segmentfault.com/a/1190000010103386
2017-07-08T16:41:43+08:00
2017-07-08T16:41:43+08:00
苏生不惑
https://segmentfault.com/u/sushengbuhuo
35
<h3>图片处理</h3>
<pre><code class="js">pip install pillow
from PIL import Image
import numpy as np
a = np.array(Image.open('test.jpg'))
b = [255,255,255] - a
im = Image.fromarray(b.astype('uint8'))
im.save('new.jpg')</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=fhJ7Ggnjhi20N8%2BZvIwYYQ%3D%3D.6XhH2b9B%2BO1UCFBPn8j4MQ8CDQd3GR4%2Fhmce2O44zlLQEHX7Hm2JYLiHyirdztrWs5lxhARULl9F7xkELN5hHw%3D%3D" rel="nofollow">Parse Redis dump.rdb</a></h3>
<pre><code class="js">pip install rdbtools
> rdb --command json /var/redis/6379/dump.rdb
[{
"user003":{"fname":"Ron","sname":"Bumquist"},
"lizards":["Bush anole","Jackson's chameleon","Komodo dragon","Ground agama","Bearded dragon"],
"user001":{"fname":"Raoul","sname":"Duke"},
"user002":{"fname":"Gonzo","sname":"Dr"},
"user_list":["user003","user002","user001"]},{
"baloon":{"helium":"birthdays","medical":"angioplasty","weather":"meteorology"},
"armadillo":["chacoan naked-tailed","giant","Andean hairy","nine-banded","pink fairy"],
"aroma":{"pungent":"vinegar","putrid":"rotten eggs","floral":"roses"}}]</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=GafKRFS881WVxz%2BVRPubbw%3D%3D.0KFCFE7fRVBvl%2BDs%2FK4q49FLxAWF86ikRJ7pyNClq%2FJ7QT7%2BSa3dMjUU7P9%2FaYny" rel="nofollow">youtube-dl下载国外视频</a></h3>
<pre><code class="js">pip install youtube-dl #直接安装youtube-dl
pip install -U youtube-dl #安装youtube-dl并更新
youtube-dl "http://www.youtube.com/watch?v=-wNyEUrxzFU"</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=1RYejxQl1Vswbnf93S%2FBXg%3D%3D.IfvcGareb1OzU%2B%2BSHPizHDJXZhIIHTHb6Zv6kgLAyS7BacfJE7bS18b4sRy5VDg2J52vDT5B8QlnLTIijPMwoA%3D%3D" rel="nofollow">asciinema录制命令行操作</a></h3>
<pre><code class="js">pip3 install asciinema
asciinema rec
asciinema play https://asciinema.org/a/132560
<script type="text/javascript" src="https://asciinema.org/a/132560.js"
id="asciicast-132560" async></script></code></pre>
<h3>查看对象的全部属性和方法</h3>
<pre><code class="js">pip install pdir2
>>> import pdir,requests
>>> pdir(requests)
module attribute:
__cached__, __file__, __loader__, __name__, __package__, __path__, __spec__
other:
__author__, __build__, __builtins__, __copyright__, __license__, __title__,
__version__, _internal_utils, adapters, api, auth, certs, codes, compat, cookies
, exceptions, hooks, logging, models, packages, pyopenssl, sessions, status_code
s, structures, utils, warnings
special attribute:
__doc__
class:
NullHandler: This handler does nothing. It's intended to be used to avoid th
e
PreparedRequest: The fully mutable :class:`PreparedRequest <PreparedRequest>
` object,
Request: A user-created :class:`Request <Request>` object.
Response: The :class:`Response <Response>` object, which contains a
Session: A Requests session.
exception:
ConnectTimeout: The request timed out while trying to connect to the remote
server.
ConnectionError: A Connection error occurred.
DependencyWarning: Warned when an attempt is made to import a module with mi
ssing optional
FileModeWarning: A file was opened in text mode, but Requests determined its
binary length.
HTTPError: An HTTP error occurred.
ReadTimeout: The server did not send any data in the allotted amount of time
.
RequestException: There was an ambiguous exception that occurred while handl
ing your
Timeout: The request timed out.
TooManyRedirects: Too many redirects.
URLRequired: A valid URL is required to make a request.
function:
delete: Sends a DELETE request.
get: Sends a GET request.
head: Sends a HEAD request.
options: Sends a OPTIONS request.
patch: Sends a PATCH request.
post: Sends a POST request.
put: Sends a PUT request.
request: Constructs and sends a :class:`Request <Request>`.
session: Returns a :class:`Session` for context-management.</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=BIIi2%2Bdul%2FkvOSxfKmGDNA%3D%3D.iTskxX5f%2F%2FJ3GStxjzcQNz7kNDbJXMV56wK2Y3xh0OrnaUmlCq5F1F6AnfpogYL6" rel="nofollow">Python 玩转网易云音乐</a></h3>
<pre><code class="js">#https://github.com/ziwenxie/netease-dl pip install netease-dl
pip install ncmbot
import ncmbot
#登录
bot = ncmbot.login(phone='xxx', password='yyy')
bot.content # bot.json()
#获取用户歌单
ncmbot.user_play_list(uid='36554272')</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=AlMaanxEa2MkMJHR3afS%2Fw%3D%3D.WZdbhh5vRegRkPTUiRWtHDZVL9eyI2MmHh9VNecXyEVzkgLzVVjmrsVIsunSLpOA" rel="nofollow">下载视频字幕</a></h3>
<pre><code class="js">pip install getsub</code></pre>
<p><img src="/img/bVQyrj?w=764&h=394" alt="clipboard.png" title="clipboard.png"></p>
<h3><a href="https://link.segmentfault.com/?enc=6WTvXNuGUocYJIqN2HX5Zw%3D%3D.HfbORdd2xJviTXoCf%2B8NdyzbZ2uNxOU6aqVFWhbXGDryIgkvb93%2BJTRtril6vNSx" rel="nofollow">Python 财经数据接口包</a></h3>
<pre><code class="js">pip install tushare
import tushare as ts
#一次性获取最近一个日交易日所有股票的交易数据
ts.get_today_all()
代码,名称,涨跌幅,现价,开盘价,最高价,最低价,最日收盘价,成交量,换手率
code name changepercent trade open high low settlement \
0 002738 中矿资源 10.023 19.32 19.32 19.32 19.32 17.56
1 300410 正业科技 10.022 25.03 25.03 25.03 25.03 22.75
2 002736 国信证券 10.013 16.37 16.37 16.37 16.37 14.88
3 300412 迦南科技 10.010 31.54 31.54 31.54 31.54 28.67
4 300411 金盾股份 10.007 29.68 29.68 29.68 29.68 26.98
5 603636 南威软件 10.006 38.15 38.15 38.15 38.15 34.68
6 002664 信质电机 10.004 30.68 29.00 30.68 28.30 27.89
7 300367 东方网力 10.004 86.76 78.00 86.76 77.87 78.87
8 601299 中国北车 10.000 11.44 11.44 11.44 11.29 10.40
9 601880 大连港 10.000 5.72 5.34 5.72 5.22 5.20
10 000856 冀东装备 10.000 8.91 8.18 8.91 8.18 8.10 </code></pre>
<h3><a href="https://link.segmentfault.com/?enc=o6ZJaO%2BKlMH4DPRE5SbnMg%3D%3D.SDORNPJjSFi0opVxqXwHz1hSeSsX9Bmac47m9a0P0A6xg372W%2FxQYt8iQo5%2BrlzP" rel="nofollow">开源漏洞靶场</a></h3>
<pre><code class="js"># 安装pip
curl -s https://bootstrap.pypa.io/get-pip.py | python3
# 安装docker
apt-get update && apt-get install docker.io
# 启动docker服务
service docker start
# 安装compose
pip install docker-compose
# 拉取项目
git clone git@github.com:phith0n/vulhub.git
cd vulhub
# 进入某一个漏洞/环境的目录
cd nginx_php5_mysql
# 自动化编译环境
docker-compose build
# 启动整个环境
docker-compose up -d
#测试完成后,删除整个环境
docker-compose down</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=BhAbC%2BbntmT2ShA8kOtEYw%3D%3D.ftJyFmIPaZY59ylqADoOi%2B3mm7AFLc1VWiwaouaiXBTU3%2B9YjGEPpJ7%2BfWh1oNTG" rel="nofollow">北京实时公交</a></h3>
<pre><code class="js">pip install -r requirements.txt 安装依赖
python manage.py build_cache 获取离线数据,建立本地缓存
#项目自带了一个终端中的查询工具作为例子,运行: python manage.py cli
>>> from beijing_bus import BeijingBus
>>> lines = BeijingBus.get_all_lines()
>>> lines
[<Line: 运通122(农业展览馆-华纺易城公交场站)>, <Line: 运通101(广顺南大街北口-蓝龙家园)>, ...]
>>> lines = BeijingBus.search_lines('847')
>>> lines
[<Line: 847(马甸桥西-雷庄村)>, <Line: 847(雷庄村-马甸桥西)>]
>>> line = lines[0]
>>> print line.id, line.name
541 847(马甸桥西-雷庄村)
>>> line.stations
[<Station 马甸桥西>, <Station 马甸桥东>, <Station 安华桥西>, ...]
>>> station = line.stations[0]
>>> print station.name, station.lat, station.lon
马甸桥西 39.967721 116.372921
>>> line.get_realtime_data(1) # 参数为站点的序号,从1开始
[
{
'id': 公交车id,
'lat': 公交车的位置,
'lon': 公交车位置,
'next_station_name': 下一站的名字,
'next_station_num': 下一站的序号,
'next_station_distance': 离下一站的距离,
'next_station_arriving_time': 预计到达下一站的时间,
'station_distance': 离本站的距离,
'station_arriving_time': 预计到达本站的时间,
},
...
]</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=x87mtpWw3GbjI6y1yweqqA%3D%3D.can6OK%2B9Vxvby2r3Ebs4dAQKROAJRN8rL6Aagg2HkMhTnKI0X3gL2XLQ67tpgOeF" rel="nofollow">文章提取器</a></h3>
<pre><code class="js">git clone https://github.com/grangier/python-goose.git
cd python-goose
pip install -r requirements.txt
python setup.py install
>>> from goose import Goose
>>> from goose.text import StopWordsChinese
>>> url = 'http://www.bbc.co.uk/zhongwen/simp/chinese_news/2012/12/121210_hongkong_politics.shtml'
>>> g = Goose({'stopwords_class': StopWordsChinese})
>>> article = g.extract(url=url)
>>> print article.cleaned_text[:150]
香港行政长官梁振英在各方压力下就其大宅的违章建筑(僭建)问题到立法会接受质询,并向香港民众道歉。
梁振英在星期二(12月10日)的答问大会开始之际在其演说中道歉,但强调他在违章建筑问题上没有隐瞒的意图和动机。
一些亲北京阵营议员欢迎梁振英道歉,且认为应能获得香港民众接受,但这些议员也质问梁振英有</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=yqkVPJm7uWCxsstNLapSWA%3D%3D.T4uYvvG8cgP%2FGTgBZaJODmQt4OD4j7ZddYiubnrAYM4uH5QqmdC7ZhiDUm182%2Fjw" rel="nofollow">Python 艺术二维码生成器</a></h3>
<pre><code class="js">pip install MyQR
myqr https://github.com
myqr https://github.com -v 10 -l Q</code></pre>
<p><img src="/img/bVQyu7?w=520&h=245" alt="clipboard.png" title="clipboard.png"></p>
<h3><a href="https://link.segmentfault.com/?enc=uvztqqhmn5dCirvDTK8tvw%3D%3D.3CN7evmFm4EKYtyzHXuwlqi6EtyE%2FIf3fOFw47w%2FI0jrUjRwqbvNAop75NJkqtw%2B" rel="nofollow">伪装浏览器身份</a></h3>
<pre><code class="js">pip install fake-useragent
from fake_useragent import UserAgent
ua = UserAgent()
ua.ie
# Mozilla/5.0 (Windows; U; MSIE 9.0; Windows NT 9.0; en-US);
ua.msie
# Mozilla/5.0 (compatible; MSIE 10.0; Macintosh; Intel Mac OS X 10_7_3; Trident/6.0)'
ua['Internet Explorer']
# Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; GTB7.4; InfoPath.2; SV1; .NET CLR 3.3.69573; WOW64; en-US)
ua.opera
# Opera/9.80 (X11; Linux i686; U; ru) Presto/2.8.131 Version/11.11
ua.chrome
# Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.2 (KHTML, like Gecko) Chrome/22.0.1216.0 Safari/537.2'</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=MnE1Pfo9El4obduJTN%2FXog%3D%3D.Shrn0%2BOgWp37RD1XK8LruJMAK9mD4xun%2FI%2Fk1aGuJ4c1Q%2Fs7lvz0Ag4SBeJGMOl9" rel="nofollow">美化 curl</a></h3>
<pre><code class="js">pip install httpstat
httpstat httpbin.org/get</code></pre>
<p><img src="/img/bVQywG?w=865&h=521" alt="clipboard.png" title="clipboard.png"></p>
<h3><a href="https://link.segmentfault.com/?enc=1Sb2n8XPDkQ3JqLf%2BiqlwQ%3D%3D.Q5IJYzn5xIK52xYHXMOvDuDyaawyGDOKJHQO1hG%2FVjg%3D" rel="nofollow">python shell</a></h3>
<pre><code class="js">pip install sh
from sh import ifconfig
print ifconfig("eth0")</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=MGpsCGEDC7DsOGez7%2BDi5g%3D%3D.WALaTcbDHkF9R1kmetwOASkQZO6%2BP59DsMKdExVNjecn4gDmn65G%2FKmzNRVPsX%2F4" rel="nofollow">处理中文文本内容</a></h3>
<pre><code class="js">pip install -U textblob#英文文本的情感分析
pip install snownlp#中文文本的情感分析
from snownlp import SnowNLP
text = "I am happy today. I feel sad today."
from textblob import TextBlob
blob = TextBlob(text)
TextBlob("I am happy today. I feel sad today.")
blob.sentiment
Sentiment(polarity=0.15000000000000002, subjectivity=1.0)
s = SnowNLP(u'这个东西真心很赞')
s.words # [u'这个', u'东西', u'真心',
# u'很', u'赞']
s.tags # [(u'这个', u'r'), (u'东西', u'n'),
# (u'真心', u'd'), (u'很', u'd'),
# (u'赞', u'Vg')]
s.sentiments # 0.9769663402895832 positive的概率
s.pinyin # [u'zhe', u'ge', u'dong', u'xi',
# u'zhen', u'xin', u'hen', u'zan']
s = SnowNLP(u'「繁體字」「繁體中文」的叫法在臺灣亦很常見。')
s.han # u'「繁体字」「繁体中文」的叫法
# 在台湾亦很常见。'
</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=E8F5S1F%2Fv4zdx5PbZ82%2BEA%3D%3D.gAmJNRj9qylWA8%2FI4jC9jU4Yp2npw1%2FwaHvyaqAeMkFAGLAgS5umsfT6YKymSFST" rel="nofollow">抓取发放代理</a></h3>
<pre><code class="js">pip install -U getproxy
➜ ~ getproxy --help
Usage: getproxy [OPTIONS]
Options:
--in-proxy TEXT Input proxy file
--out-proxy TEXT Output proxy file
--help Show this message and exit.</code></pre>
<ul>
<li>
<code>--in-proxy</code> 可选参数,待验证的 proxies 列表文件</li>
<li>
<code>--out-proxy</code> 可选参数,输出已验证的 proxies 列表文件,如果为空,则直接输出到终端</li>
</ul>
<p><code>--in-proxy</code> 文件格式和 <code>--out-proxy</code> 文件格式一致</p>
<h3><a href="https://link.segmentfault.com/?enc=qqpYbxHkeCyV5434FgfH7w%3D%3D.uWad%2FANcekTk%2FaFDVso%2FRmdloGSyxWl0RCMAfk9eV9NVPgpuT7X9TS43LbnUgL8C" rel="nofollow">zhihu api</a></h3>
<pre><code class="js">pip install git+git://github.com/lzjun567/zhihu-api --upgrade
from zhihu import Zhihu
zhihu = Zhihu()
zhihu.user(user_slug="xiaoxiaodouzi")
{'avatar_url_template': 'https://pic1.zhimg.com/v2-ca13758626bd7367febde704c66249ec_{size}.jpg',
'badge': [],
'name': '我是小号',
'headline': '程序员',
'gender': -1,
'user_type': 'people',
'is_advertiser': False,
'avatar_url': 'https://pic1.zhimg.com/v2-ca13758626bd7367febde704c66249ec_is.jpg',
'url': 'http://www.zhihu.com/api/v4/people/1da75b85900e00adb072e91c56fd9149', 'type': 'people',
'url_token': 'xiaoxiaodouzi',
'id': '1da75b85900e00adb072e91c56fd9149',
'is_org': False}</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=mAfpiFhlq6PAtNPYfWlfUA%3D%3D.G58pCl8HZgus0hUSucaZGPujaLKAkXizWdn0H5M1J881bSTY%2FtPOHJC%2FgKoqs%2BlL" rel="nofollow">Python 密码泄露查询模块</a></h3>
<pre><code class="js">pip install leakPasswd
import leakPasswd
leakPasswd.findBreach('taobao')</code></pre>
<p><img src="/img/bVQyMN?w=1702&h=1304" alt="clipboard.png" title="clipboard.png"></p>
<h3><a href="https://link.segmentfault.com/?enc=HOQmRd%2Fz8YjM%2FnUMNinETg%3D%3D.XjX5%2F4UxPwHuL9sFQNq8ithIAOD2cL3H0VjqAthmdMEL5ccfLrjObsuoSVPt52hl" rel="nofollow">解析 nginx 访问日志并格式化输出</a></h3>
<pre><code class="js">pip install ngxtop
$ ngxtop
running for 411 seconds, 64332 records processed: 156.60 req/sec
Summary:
| count | avg_bytes_sent | 2xx | 3xx | 4xx | 5xx |
|---------+------------------+-------+-------+-------+-------|
| 64332 | 2775.251 | 61262 | 2994 | 71 | 5 |
Detailed:
| request_path | count | avg_bytes_sent | 2xx | 3xx | 4xx | 5xx |
|------------------------------------------+---------+------------------+-------+-------+-------+-------|
| /abc/xyz/xxxx | 20946 | 434.693 | 20935 | 0 | 11 | 0 |
| /xxxxx.json | 5633 | 1483.723 | 5633 | 0 | 0 | 0 |
| /xxxxx/xxx/xxxxxxxxxxxxx | 3629 | 6835.499 | 3626 | 0 | 3 | 0 |
| /xxxxx/xxx/xxxxxxxx | 3627 | 15971.885 | 3623 | 0 | 4 | 0 |
| /xxxxx/xxx/xxxxxxx | 3624 | 7830.236 | 3621 | 0 | 3 | 0 |
| /static/js/minified/utils.min.js | 3031 | 1781.155 | 2104 | 927 | 0 | 0 |
| /static/js/minified/xxxxxxx.min.v1.js | 2889 | 2210.235 | 2068 | 821 | 0 | 0 |
| /static/tracking/js/xxxxxxxx.js | 2594 | 1325.681 | 1927 | 667 | 0 | 0 |
| /xxxxx/xxx.html | 2521 | 573.597 | 2520 | 0 | 1 | 0 |
| /xxxxx/xxxx.json | 1840 | 800.542 | 1839 | 0 | 1 | 0 |</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=thqJfukg1ic3AdFDl9dhjA%3D%3D.Ym1VWS4M8LK7XKkbB2Esq844FQ0CM0B452I6P6tRo2cCIVNnUm5%2BCke0e8OLEOQu" rel="nofollow">火车余票查询</a></h3>
<pre><code class="js">pip install iquery
Usage:
iquery (-c|彩票)
iquery (-m|电影)
iquery -p <city>
iquery -l song [singer]
iquery -p <city> <hospital>
iquery <city> <show> [<days>]
iquery [-dgktz] <from> <to> <date>
Arguments:
from 出发站
to 到达站
date 查询日期
city 查询城市
show 演出的类型
days 查询近(几)天内的演出, 若省略, 默认15
city 城市名,加在-p后查询该城市所有莆田医院
hospital 医院名,加在city后检查该医院是否是莆田系
Options:
-h, --help 显示该帮助菜单.
-dgktz 动车,高铁,快速,特快,直达
-m 热映电影查询
-p 莆田系医院查询
-l 歌词查询
-c 彩票查询
Show:
演唱会 音乐会 音乐剧 歌舞剧 儿童剧 话剧
歌剧 比赛 舞蹈 戏曲 相声 杂技 马戏 魔术</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=BvgMgEjxPoG336o7KGkozA%3D%3D.58cSpCg79Swh1JC2IWVPedFQSSmV9aEJvHXumoJugUrBswIeOl2twy3op6brV63y8ZSDpaJlQ5Qpy6AxDOlDrQ%3D%3D" rel="nofollow">电脑之间传文件</a></h3>
<pre><code class="js">pip install magic-wormhole
Sender:
% wormhole send README.md
Sending 7924 byte file named 'README.md'
On the other computer, please run: wormhole receive
Wormhole code is: 7-crossover-clockwork
Sending (<-10.0.1.43:58988)..
100%|=========================| 7.92K/7.92K [00:00<00:00, 6.02MB/s]
File sent.. waiting for confirmation
Confirmation received. Transfer complete.
Receiver:
% wormhole receive
Enter receive wormhole code: 7-crossover-clockwork
Receiving file (7924 bytes) into: README.md
ok? (y/n): y
Receiving (->tcp:10.0.1.43:58986)..
100%|===========================| 7.92K/7.92K [00:00<00:00, 120KB/s]
Received file written to README.md</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=%2FBgm0UKJ4vP4sM6aduUivw%3D%3D.sPNwDpn%2BDAJnA22VItZqQM0mEXjhZkckuQMRXhD1QpKhmlc0H5RH%2FkDEhdA1JlDj" rel="nofollow">Python 数据可视化</a></h3>
<pre><code class="js">pip install pyecharts
from pyecharts import Bar
bar = Bar("我的第一个图表", "这里是副标题")
bar.add("服装", ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"], [5, 20, 36, 10, 75, 90])
bar.show_config()
bar.render()#在根目录下生成一个 render.html 的文件,用浏览器打开
#pyecharts制作词云图
from pyecharts import WordCloud
wordlist = ['Sam', 'Club','Macys', 'Amy Schumer', 'Jurassic World', 'Charter','Communications','Chick Fil A', 'Planet Fitness', 'Pitch Perfect', 'Express', 'Home', 'Johnny Depp','Lena Dunham', 'Lewis', 'Hamilton','KXAN', 'Mary Ellen Mark', 'Farrah','Abraham','Rita Ora', 'Serena Williams', 'NCAA', ' baseball',' tournament','Point Break']
#对应于wordlist中每个元素的词频
freq = [10000, 6181, 6000, 4386, 4055, 2467, 2244, 1898, 1484, 1112,1112,1112, 965, 847, 847, 555, 555,555,550, 462, 366, 360, 282, 273, 265]
#设置图标尺寸大小
wordcloud = WordCloud(width=1000, height=620)
wordcloud.add(name="",
attr=wordlist,
shape='circle',
value=freq,
word_size_range=[20, 100])
#notebook上渲染出词云图
wordcloud
#将词云图渲染并保存到html文件中
#wordcloud.render(path='词云图.html')
freq = [7000, 6181, 6000, 4386, 4055, 2467, 2244, 1898, 1484, 1112,1112,1112, 965, 847, 847, 555, 555,555,550, 462, 366, 360,299, 10000, 7000]
wordcloud = WordCloud(width=1000, height=620)
wordcloud.add(name="",
attr=wordlist,
shape='star',
value=freq,
word_size_range=[20, 100])
wordcloud</code></pre>
<p><img src="/img/bVRpF3?w=824&h=390" alt="clipboard.png" title="clipboard.png"></p>
<h3><a href="https://link.segmentfault.com/?enc=Skgddrp9ivrck%2FKz2hhFoQ%3D%3D.BCn2hnCxtkqwM%2F%2Ben7iW3EpQrJAHaz791czSLtlNRE3KRbwhNs8J1VOqBykIFkEI" rel="nofollow">微信公众号爬虫接口</a></h3>
<pre><code class="js">pip install wechatsogou
from wechatsogou import *
wechats = WechatSogouApi()
name = '南京航空航天大学'
wechat_infos = wechats.search_gzh_info(name)</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=aFarJjV8UTs5YB5ae436Sw%3D%3D.y0sycWAdgHWFjEvSKXQnTHBMGxkwEJutnx5PK8kQSc5ViKe7%2BPfkbUpUZiFHNJp7" rel="nofollow">优雅的重试</a></h3>
<pre><code class="js">pip install tenacity
#限制重试次数为3次
from tenacity import retry, stop_after_attempt
@retry(stop=stop_after_attempt(3))
def extract(url):
info_json = requests.get(url).content.decode()
info_dict = json.loads(info_json)
data = info_dict['data']
save(data)</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=uxNl0yrn6xyZ7UBwIILwvA%3D%3D.sBu0JqlCAB%2BZFb%2FzeHgQN1dJJRCLe1j11e1lW7XaQKnxg%2FMh7OEpf81vz%2Fdnhlmd" rel="nofollow">查找IP地址归属地</a></h3>
<pre><code class="js">pip install qqwry-py3
from qqwry import QQwry
q = QQwry()
q.load_file('qqwry.dat', loadindex=False)
result = q.lookup('8.8.8.8') </code></pre>
<h3><a href="https://link.segmentfault.com/?enc=3Gr0Hs0cZMNBYf7ppwRoig%3D%3D.aAFSA0fqPAiMK1pqCfJPPNC80bRVfzquSPzdMnLe6pk%3D" rel="nofollow">导出 python 库列表</a></h3>
<pre><code class="js">#pip freeze 导出当前环境中所有的 python 库列表
$ pip install pipreqs
$ pipreqs /home/project/location
Successfully saved requirements file in /home/project/location/requirements.txt</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=c6srw4wrSn8456ZVYQA6Ow%3D%3D.%2Fe90yU18TPKFsEeSv0V%2BL%2FQF6IfF4FJDbuZXd4oQdDqGVmYVnqgslC1DXEoehbyo" rel="nofollow">Google Chrome Dev Protocol</a></h3>
<pre><code class="js">pip install -U pychrome
google-chrome --remote-debugging-port=9222
# create a browser instance
browser = pychrome.Browser(url="http://127.0.0.1:9222")
# list all tabs (default has a blank tab)
tabs = browser.list_tab()
if not tabs:
tab = browser.new_tab()
else:
tab = tabs[0]
# register callback if you want
def request_will_be_sent(**kwargs):
print("loading: %s" % kwargs.get('request').get('url'))
tab.Network.requestWillBeSent = request_will_be_sent
# call method
tab.Network.enable()
# call method with timeout
tab.Page.navigate(url="https://github.com/fate0/pychrome", _timeout=5)
# 6. wait for loading
tab.wait(5)
# 7. stop tab (stop handle events and stop recv message from chrome)
tab.stop()
# 8. close tab
browser.close_tab(tab)</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=goC%2B5RFyocPR%2Fc%2FUj9epww%3D%3D.k1L4j9cXCeIbVsPLmQecgFaW2wB1M3j%2FF%2BTxhyB%2FuA%2Ft2i9RU6glTo8Dl4ac%2FGfA" rel="nofollow">模糊搜索</a></h3>
<pre><code class="js">pip install fuzzywuzzy
>>> from fuzzywuzzy import fuzz
>>> from fuzzywuzzy import process
>>> fuzz.ratio("this is a test", "this is a test!")
97
>>> choices = ["Atlanta Falcons", "New York Jets", "New York Giants", "Dallas Cowboys"]
>>> process.extract("new york jets", choices, limit=2)
[('New York Jets', 100), ('New York Giants', 78)]
>>> process.extractOne("cowboys", choices)
("Dallas Cowboys", 90)</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=wdJWGxn7%2BIOj6YAIl2z0iw%3D%3D.AYduH3Owy%2FEAXNUPGvyoYC12vTPdAoOyh2qTR2Qmjxa8y4eX0pqUvf9gNPZ%2FVPKD" rel="nofollow">算法学习</a></h3>
<pre><code class="js">from pygorithm.sorting import bubble_sort
myList = [12, 4, 3, 5, 13, 1, 17, 19, 15]
sortedList = bubble_sort.sort(myList)
print(sortedList)
[1, 3, 4, 5, 12, 13, 15, 17, 19]</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=LLaUC6GOPFr3p%2FuzkM3HMQ%3D%3D.kkIHQdeaDV6NNHHSucJqhJ2g90pBON%2FHsUo1mA9TMvaj%2FHzHwFYMzNAcmAdKDnId" rel="nofollow">命令行洪流搜索程序</a></h3>
<pre><code class="js">pip install torrench --upgrade
$ torrench "ubuntu desktop 16.04" ## Search Linuxtracker for Ubuntu Desktop 16.04 distro ISO
$ torrench "fedora workstation" ## Search for Fedora Workstation distro ISO
$ torrench -d "opensuse" ## Search distrowatch for opensuse ISO
$ torrench -d "solus" ## Search distrowatch for solus ISO</code></pre>
<p><img src="/img/bVTMvo?w=1055&h=646" alt="clipboard.png" title="clipboard.png"></p>
<h3><a href="https://link.segmentfault.com/?enc=d7xm5TpjGMPdrRWWJkZ54g%3D%3D.eqTgHS6n3ZWK5KynXRo%2FcvUg9LJjFoeknjGA%2BAbUzbSRG26Xd4MFR1LbzzQKIHwm" rel="nofollow">根据姓名来判断性别</a></h3>
<pre><code class="js">pip install ngender
$ ng 赵本山 宋丹丹
name: 赵本山 => gender: male, probability: 0.9836229687547046
name: 宋丹丹 => gender: female, probability: 0.9759486128949907
>>> import ngender
>>> ngender.guess('赵本山')
('male', 0.9836229687547046)</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=dg%2BqgDekQ17bbykHQl4hHg%3D%3D.eEApXrxlQ716VOOI3ehd8VgeVMvfdTz1mHWYYNuhOTilhSZkC65r22DjDWQ%2FgWDj" rel="nofollow">Python编写的简单的微信客户端</a></h3>
<pre><code class="js">#https://github.com/pavlovai/match
pip install pywxclient
pip install git+https://github.com/justdoit0823/pywxclient
>>> from pywxclient.core import Session, SyncClient
>>> s1 = Session()
>>> c1 = SyncClient(s1)
>>> c1.get_authorize_url() # Open the url in web browser
>>> c1.authorize() # Continue authorize when returning False
>>> c1.login()
>>> c1.sync_check()
>>> msgs = c1.sync_message() # Here are your wechat messages
>>> c1.flush_sync_key()</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=NfEVy%2BYkUidNIPGHUvtUWQ%3D%3D.tAOJ1PzGfWjIjK%2BbIK1NEyFpx776lxOzCXjXvmBYu%2F%2FUjzEgI0jp2ndFZP%2FRefF7XPFv%2BEOUZJAxzd6a7VAKAw%3D%3D" rel="nofollow">比较相似图片</a></h3>
<pre><code class="js">$ pip install numpy
$ pip install scipy
$ pip install image_match
from image_match.goldberg import ImageSignature
gis = ImageSignature()
a = gis.generate_signature('https://upload.wikimedia.org/wikipedia/commons/thumb/e/ec/Mona_Lisa,_by_Leonardo_da_Vinci,_from_C2RMF_retouched.jpg/687px-Mona_Lisa,_by_Leonardo_da_Vinci,_from_C2RMF_retouched.jpg')
b = gis.generate_signature('https://pixabay.com/static/uploads/photo/2012/11/28/08/56/mona-lisa-67506_960_720.jpg')
gis.normalized_distance(a, b)</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=WcPJyV%2BaktLHXN6u5q%2B5RQ%3D%3D.pX63M3ESMoZtQnGGDmr5AffLb9%2Bb4Vp7BOfFZdL7dpfPU%2BtCc%2B6tZGHd8TkZ%2F%2Fh9" rel="nofollow">身份证识别OCR</a></h3>
<h3><a href="https://link.segmentfault.com/?enc=ixH16pJ3xJqdF%2FC8xsVAQA%3D%3D.6wQvXdGDW4Nfgq6rUarG%2FBfL63c1gGT9M%2Bkj11Jj0nTnAQQjzVW8RkQziexco5tB" rel="nofollow">生成各类虚拟数据</a></h3>
<pre><code class="js">pip install mimesis
>>> import mimesis
>>> person = mimesis.Personal(locale='en')
>>> person.full_name(gender='female')
'Antonetta Garrison'
>>> person.occupation()
'Backend Developer'</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=ahySKh2n0gx0RVcCB7woBw%3D%3D.7Z7ObxxphtV70Ta%2BWJGv4rmpkXGgXOht5CQ1Aw5I2Ujq%2BUPtUkQITBPDFEibg7Ki" rel="nofollow">视频处理库</a></h3>
<pre><code class="js">from moviepy.editor import *
video = VideoFileClip("myHolidays.mp4").subclip(50,60)
# Make the text. Many more options are available.
txt_clip = ( TextClip("My Holidays 2013",fontsize=70,color='white')
.set_position('center')
.set_duration(10) )
result = CompositeVideoClip([video, txt_clip]) # Overlay text on video
result.write_videofile("myHolidays_edited.webm",fps=25) # Many options...</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=9eZgQP1NtdVp7HCUB1a1xQ%3D%3D.lGK5WTR0UJYvThB%2FQ91TxBi24LRxh58uq7J%2Fqvi792IitVPPvzad8JcP9mi5%2Bne9" rel="nofollow">微信聊天记录导出、分析工具</a></h3>
<pre><code class="js">pip install wechat-explorer
wexp list_chatrooms ../Documents user_id
wexp list_friends ../Documents user_id
wexp get_chatroom_stats ../Documents user_id chatroom_id@chatroom 2015-08-01 2015-09-01
wexp export_chatroom_records ../Documents user_id chatroom_id@chatroom 2015-10-01 2015-10-07 ../
wexp get_friend_label_stats ../Documents user_id
wkhtmltopdf --dpi 300 records.html records.pdf</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=AxXVywqNH%2FeTnSxM0s3lnw%3D%3D.e%2FZBLiOwlRVRNk%2Byw03oqDyD9DQku%2Bo4OFrFK%2F%2FeUwdRD6n35QaroXjFLkke2HS%2Fj8SEulGhbRyx35HQBxTJoA%3D%3D" rel="nofollow">图片爬虫库</a></h3>
<pre><code class="js">pip install icrawler
from icrawler.builtin import BaiduImageCrawler, BingImageCrawler, GoogleImageCrawler
google_crawler = GoogleImageCrawler(parser_threads=2, downloader_threads=4,
storage={'root_dir': 'your_image_dir'})
google_crawler.crawl(keyword='sunny', offset=0, max_num=1000,
date_min=None, date_max=None,
min_size=(200,200), max_size=None)
bing_crawler = BingImageCrawler(downloader_threads=4,
storage={'root_dir': 'your_image_dir'})
bing_crawler.crawl(keyword='sunny', offset=0, max_num=1000,
min_size=None, max_size=None)
baidu_crawler = BaiduImageCrawler(storage={'root_dir': 'your_image_dir'})
baidu_crawler.crawl(keyword='sunny', offset=0, max_num=1000,
min_size=None, max_size=None)
from icrawler.builtin import GreedyImageCrawler
storage= {'root_dir': '/'}
greedy_crawler = GreedyImageCrawler(storage=storage)
greedy_crawler.crawl(domains='http://qq.com',
max_num=6)</code></pre>
<h3>Python 剪贴板</h3>
<pre><code class="js">pip install pyperclip
from pyperclip import copy, paste
copy('2333') # 向剪贴板写入 2333
paste() # 值为剪贴板中的内容 </code></pre>
<h3><a href="https://link.segmentfault.com/?enc=%2FfM5kaSM21OQThgp2XkjJA%3D%3D.54uTUb3aYBQsBQ9RCtwyrI8xHCoc%2B2ma1Xlg1urQfgziBpAtZ%2BW86JH6ogcRoWOy" rel="nofollow">获取图片的相似度</a></h3>
<pre><code class="js">import face_recognition
image = face_recognition.load_image_file("your_file.jpg")
face_locations = face_recognition.face_locations(image)</code></pre>
<p><img src="/img/bVYi2C?w=563&h=366" alt="clipboard.png" title="clipboard.png"></p>
<h3><a>浏览器自动化splinter</a></h3>
<pre><code class="js">#chromedriver.storage.googleapis.com/index.html
>>> from splinter.browser import Browser
>>> xx = Browser(driver_name="chrome")
>>> xx.visit("http://www.zhihu.com/")</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=qR0O7N810Pr7LQCEuVrU2Q%3D%3D.gYUbOC8rCOlyfk8OL594qVUE82blUPICNiWNlVIjNMGcTkxr10C0aYuFo9PUquBi" rel="nofollow">为SQLite数据库生成JSON</a></h3>
<pre><code class="js">pip3 install datasette
datasette serve path/to/database.db
http://localhost:8001/History/downloads.json</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=HBpQmK%2BvbuVJeWnuGGCmoQ%3D%3D.CbbqK7OeDhnS5rxPLxb6vsyvjJp%2F4AWcBnaPeXpHHqg%3D" rel="nofollow">numpy 接口直接工作在 CUDA</a></h3>
<pre><code class="js">>>> import cupy as cp
>>> x = cp.arange(6).reshape(2, 3).astype('f')
>>> x
array([[ 0., 1., 2.],
[ 3., 4., 5.]], dtype=float32)
>>> x.sum(axis=1)
array([ 3., 12.], dtype=float32)</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=pQsP0yXz2fC2j%2BrSoLsJOg%3D%3D.9inW2QoORtTqDYeBYppD0NLAElTtLl9NopOVZjqBet4Pkn7I2D82fpg5FlOLYqgV" rel="nofollow">了解一个命令或程序在执行前会做什么</a></h3>
<pre><code class="js">pip install maybe
maybe rm -r ostechnix/
maybe has prevented rm -r ostechnix/ from performing 5 file system operations:
delete /home/sk/inboxer-0.4.0-x86_64.AppImage
delete /home/sk/Docker.pdf
delete /home/sk/Idhayathai Oru Nodi.mp3
delete /home/sk/dThmLbB334_1398236878432.jpg
delete /home/sk/ostechnix
Do you want to rerun rm -r ostechnix/ and permit these operations? [y/N] y</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=25qfBJw%2Fge%2FDeq2DF9B8uA%3D%3D.1WY8%2FnyDNCodClHxNQxR0l4rxZZKg%2B7DzzsXn6coxnk%3D" rel="nofollow">获取ip</a></h3>
<pre><code class="js">pip install ng
$ ng ip
local_ip:192.168.1.114
public_ip:49.4.160.250
$ ng wp
$ ng wp flyfish_5g
flyfish_5g:hitflyfish123456</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=FxdlvIZZes%2BLX6SRYMmfjg%3D%3D.%2FQLva%2B6o1V1e%2BUWrx24O0z6U4BRO91batpp54YROXCI%3D" rel="nofollow">图床服务</a></h3>
<pre><code class="js">$ pip install qu
$ qu up /somewhere/1.png
$ qu up /somewhere/1.png 2.png</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=blmyBxB8%2BmTOcGAon2LAxw%3D%3D.NkI9e9nPHgQXBMdxV5T98fc365Z92oJq7VXvtjYSKIQ%3D" rel="nofollow">get .gitignore</a></h3>
<pre><code class="js">#https://www.gitignore.io/
$ pip install gy
$ gy generate python java lisp</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=yotum5PKkVtUZ2dOAIm1SA%3D%3D.pAy%2BLHWOrAHaPl%2Bnz5gzD5XC1nuNziIZ35dBA%2BdfZwb9Af0biteF9L0dd9pmsOhXf2zJPTB%2BesX4cadF%2Bh6QSA%3D%3D" rel="nofollow">PyGithub</a></h3>
<pre><code class="js">pip install PyGithub
from github import Github
g = Github("xxxxx", "passwd")
my_forks = []
for repo in g.get_user().get_repos():
if repo.fork:
my_forks.append(repo)
</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=3m74VuWw5GuzeKgdkiUp9g%3D%3D.C3IdMLkEn7g7kmWcK8jKpJIdsX2HEqt7phGw8stZ4KaDmLES9xZp6w3XKvhE02xo" rel="nofollow">爬虫小工具</a></h3>
<pre><code class="js">pip install lazyspider
from lazyspider.lazyheaders import LazyHeaders
# 注意!字符串要包裹在 三引号 或 双引号 里
curl = "curl 'https://pypi.python.org/pypi' -H 'cookie: .....balabala...."
lh = LazyHeaders(curl)
headers = lh.getHeaders()
cookies = lh.getCookies()
print('*' * 40)
print('Headers: {}'.format(headers))
print('*' * 40)
print('Cookies: {}'.format(cookies))
print('*' * 40)
import requests
r = requests.get('https://pypi.python.org/pypi',
headers=headers, cookies=cookies)
print(r.status_code)
</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=2Qxv2%2F7KVo4nPeGcLjehVw%3D%3D.UXNs5sJjaOU8gj7BSChy18yqBT8y2ZPIqca%2BYRjnpM0itFlFUHzXARIOkPQtXKt2" rel="nofollow">中文近义词工具包</a></h3>
<pre><code class="js">pip install -U synonyms
>>> synonyms.display("飞机")
'飞机'近义词:
1. 架飞机:0.837399
2. 客机:0.764609
3. 直升机:0.762116
4. 民航机:0.750519
5. 航机:0.750116
6. 起飞:0.735736
7. 战机:0.734975
8. 飞行中:0.732649
9. 航空器:0.723945
10. 运输机:0.720578</code></pre>
<p>公众号:苏生不惑</p>
<p><img src="/img/bVOYWr?w=425&h=433" alt="clipboard.png" title="clipboard.png"></p>
阿里云 Ubuntu PHP7 Nginx Mysql 开发环境搭建
https://segmentfault.com/a/1190000009916409
2017-06-24T21:48:57+08:00
2017-06-24T21:48:57+08:00
苏生不惑
https://segmentfault.com/u/sushengbuhuo
15
<p>记录下在阿里云搭建 PHP7 开发环境</p>
<h3>安装 nginx</h3>
<pre><code class="js">sudo apt-get update
sudo apt-get install nginx
安装完成后会自动开启,通过命令查看
# ps -aux |grep nginx
root 7921 0.0 0.0 14232 972 pts/0 S+ 21:25 0:00 grep --color=au
to nginx
root 27770 0.0 0.0 117084 1444 ? Ss 20:39 0:00 nginx: master p
rocess /usr/sbin/nginx -g daemon on; master_process on;
www-data 27771 0.0 0.0 117404 3084 ? S 20:39 0:00 nginx: worker p
rocess
www-data 27772 0.0 0.1 117692 5120 ? S 20:39 0:00 nginx: worker p
rocess
浏览器打开 http://x.x.x.x.com/ 可以看到 nginx 的欢迎页面</code></pre>
<p><img src="/img/bVPLOL?w=527&h=212" alt="clipboard.png" title="clipboard.png"></p>
<h3>安装 PHP7</h3>
<pre><code class="js">sudo apt-get install python-software-properties software-properties-common
sudo add-apt-repository ppa:ondrej/php
sudo apt-get install php7.0-fpm php7.0-cli php7.0-mcrypt php7.0-mysql php7.0-mbstring php7.0-xml php7.0-curl
开启OPcache
apt-get install php70-php-opcache.x86_64
sudo service php7.0-fpm restart</code></pre>
<h3>配置 nginx 解析 PHP</h3>
<pre><code class="js">vi /etc/nginx/sites-available/default
server {
listen 80 default_server;
listen [::]:80 default_server ipv6only=on;
#root 为项目代码所在目录
root /var/www/html;
index index.php index.html index.htm;
#填写购买的阿里云外网IP或者自己已经解析备案的域名
server_name http://x.x.x.x/;
#更改未被注释一行
location / {
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
try_files $uri $uri/ =404;
# Uncomment to enable naxsi on this location
# include /etc/nginx/naxsi.rules
}
#添加下面代码
location ~ \.php$ {
try_files $uri $uri/ =404;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
sudo vi /etc/php/7.0/fpm/php.ini
cgi.fix_pathinfo=0
sudo phpenmod mcrypt
sudo service php7.0-fpm restart
sudo service nginx restart
vi test.php
<?php
phpinfo();
</code></pre>
<p><img src="/img/bVPLP5?w=953&h=569" alt="clipboard.png" title="clipboard.png"></p>
<h3>安装 MySQL</h3>
<pre><code class="js"># 默认安装 MySQL 5.7
sudo apt-get install mysql-server mysql-client
#设置好密码后登陆
mysql -u root -p</code></pre>
<h3>安装 redis</h3>
<pre><code class="js">sudo apt-get install git
git clone -b php7 https://github.com/phpredis/phpredis.git
mv phpredis/ /etc/
cd /etc/phpredis
sudo apt install php7.0-dev
#生成编译文件
phpize
sudo ./configure
make && make install
find / -name redis.so
/etc/phpredis/.libs/redis.so
/etc/phpredis/modules/redis.so
/usr/lib/php/20151012/redis.so
vim /etc/php/7.0/apache2/php.ini
extension=/etc/phpredis/modules/redis.so
sudo service php7.0-fpm restart
ps -aux |grep redis
root 7981 0.0 0.0 14232 1024 pts/0 S+ 21:40 0:00 grep --color=auto redis
redis 30952 0.0 0.1 40136 6716 ? Ssl 20:59 0:02 /usr/bin/redis-server 127.0.0.1:6379
redis-cli
127.0.0.1:6379> info
# Server
redis_version:3.0.6
redis_git_sha1:00000000
redis_git_dirty:0
redis_build_id:687a2a319020fa42
redis_mode:standalone
os:Linux 4.4.0-79-generic x86_64
arch_bits:64
multiplexing_api:epoll
gcc_version:5.3.1
process_id:30952
run_id:056f34665607470e822036784d93cbbe079080a7
tcp_port:6379
uptime_in_seconds:2792
uptime_in_days:0
vi test.php
<?php
//连接本地Redis服务
$redis=new Redis();
$redis->connect('127.0.0.1','6379');</code></pre>
<h3>上传代码</h3>
<pre><code class="js">scp -r . root@x.x.x.x:/var/www/html
</code></pre>
<p>参考<br><a href="https://link.segmentfault.com/?enc=V2Ixu5ycENgtUkwDVu%2FMag%3D%3D.dzDiV9CvEKMHagmV20Bh9X2Y6hcfyVIumxZtoQ%2Fn%2BYS3su%2BKHFQaDZJJe079QgC9" rel="nofollow">阿里云Ubuntu14+PHP7+Nginx+Mysql环境搭建</a><br><a href="https://link.segmentfault.com/?enc=pGH3j91cr5B3dmoF2Dzxpg%3D%3D.JmwM%2B%2FjHH3SG47SQOwyZC1W55CV1IF7P7NzSYuVTZOqh0nDCL9xIzNCQAQ3YMgf8OBr8E5f1s5cd5Zkb3D5VlL2NPrBmv4FV5iDqhiZ4VYs%3D" rel="nofollow">在阿里云上部署Laravel应用</a><br><a href="https://link.segmentfault.com/?enc=PNjB%2F8X1ikSxzm05isbTkA%3D%3D.R8BM7dy%2FDGpA%2FDr9mPh5B%2BTz%2FDjBNdgAJePhPbi9VPJzfAkaWVmik7ADS1vf0LjV" rel="nofollow">阿里云ECS部署Laravel+PHP7+Nginx</a><br><a href="https://link.segmentfault.com/?enc=NnLCnC8clX1I8OEe%2FRE3zA%3D%3D.4MV5Y%2FQr9qLzNvARRZHysOrSNk0Uhn8Lr1ORuzrYFCtnv7%2FLJO2eA6YhTVncQV3n" rel="nofollow">Nginx配置https访问</a></p>
命令行神器推荐
https://segmentfault.com/a/1190000009728316
2017-06-10T12:54:22+08:00
2017-06-10T12:54:22+08:00
苏生不惑
https://segmentfault.com/u/sushengbuhuo
13
<p>作为程序员都习惯在命令行下操作,今天就推荐些命令行神器,可能让你大开眼界。</p>
<h3>统计当前目录代码数 line-counter</h3>
<pre><code class="js">//https://github.com/MorganZhang100/line-counter
//find . -name '*.py' -exec wc -l {} +
//wc -l
pip install line-counter
$ line
Search in /Users/Morgan/Documents/Example/
file count: 4
line count: 839
$ line -d
Search in /Users/Morgan/Documents/Example/
Dir A/file C.c 72
Dir A/file D.py 268
file A.py 467
file B.c 32
file count: 4
line count: 839
//https://github.com/AlDanial/cloc
npm install -g cloc
$ cloc wechat-cli.py
1 text file.
1 unique file.
0 files ignored.
github.com/AlDanial/cloc v 1.72 T=0.14 s (7.4 files/s, 779.4 lines/s)
-------------------------------------------------------------------------------
Language files blank comment code
-------------------------------------------------------------------------------
Python 1 12 7 87
-------------------------------------------------------------------------------</code></pre>
<h3>命令行纠错 thefuck</h3>
<pre><code class="js">//https://github.com/nvbn/thefuck
pip install thefuck
➜ apt-get install vim
E: Could not open lock file /var/lib/dpkg/lock - open (13: Permission denied)
E: Unable to lock the administration directory (/var/lib/dpkg/), are you root?
➜ fuck
sudo apt-get install vim
[sudo] password for nvbn:
Reading package lists... Done</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=JVwiDPBn1DLh6SHedDzhSA%3D%3D.u2eTldiScXGvBMQBcmsTuoaBLeVl%2F6zdyRQdlDJ4gXfYO19zlnVL8NxVqC49BkB5" rel="nofollow">markdown to html </a></h3>
<pre><code class="js">npm install -g codedog
codedog xx.md or codedog xx.md width height</code></pre>
<h3>mysql 客户端,支持语法高亮和命令补全 mycli</h3>
<pre><code class="js">// https://github.com/dbcli/mycli
pip install -U mycli
$ mycli -h localhost -uroot
Password:
Version: 1.8.0
Chat: https://gitter.im/dbcli/mycli
Mail: https://groups.google.com/forum/#!forum/mycli-users
Home: http://mycli.net
Thanks to the contributor - Tech Blue Software
mysql root@localhost:(none)> use test
You are now connected to database "test" as user "root"
Time: 0.005s
mysql root@localhost:test> show t
TABLE STATUS
TABLE STATUS
TABLES
TABLES
TRIGGERS
TRIGGERS
STATUS
[F2] Smart Completion: ON [F3] Multiline: OFF [F4] Emacs-mode</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=JPUwbdAi9mEzPqqylKNd0w%3D%3D.XiWtzjgljOVYQnsML6njncKoF2PZq0qUxXGg7f1UvOkZw7stdr7wh88xlq%2B82Joh" rel="nofollow">基于puppeteer的网页截图工具</a></h3>
<pre><code class="js">$ npm install -g vian
(1)截取 github 首页
$ vian https://github.com
(2)截取 github 首页 (非全屏)
$ vian --no-fullpage https://github.com
(3)保存 github 首页为图片,模拟 iPhone 6
$ vian -d 'iPhone 6' -f github.jpg https://github.com
(4)保存 github 首页为 pdf 文档,纸张尺寸选择 A4
$ vian -t pdf -s A4 https://github.com
(5)查看所有的可模拟设备
$ vian devices
//https://github.com/Runjuu/page2image
npm i page2image --global
# Single page
> page2image https://github.com/Runjuu --type=jpeg --quality=80
# Multi-page
> page2image https://github.com/Runjuu https://github.com/Runjuu --type=jpeg --quality=80</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=wC8AdzpSILIEav2y63T34Q%3D%3D.BIoUnZeP5rJcMmlKpdd4nHt6SXtKNy%2BZaMaA%2BmLsDLLad9WkZXutTsLqbdIbIBBx" rel="nofollow">一个生成pdf文件的微服务</a></h3>
<p><code>npm install -g pdf-bot</code></p>
<h3>json文件处理以及格式化显示,支持高亮,可以替换python -m json.tool</h3>
<pre><code class="js">//https://github.com/stedolan/jq http://blog.chinaunix.net/uid-24774106-id-3830242.html
$ cat json_raw.txt
{"name":"Google","location":{"street":"1600 Amphitheatre Parkway","city":"Mountain View","state":"California","country":"US"},"employees":[{"name":"Michael","division":"Engineering"},{"name":"Laura","division":"HR"},{"name":"Elise","division":"Marketing"}]}
cat json_raw.txt | jq '.location.state'
"California"
echo '{"foo": 42, "bar": "less interesting data"}' | jq .nofoo
null
cat json_raw.txt | jq 'keys'
[
"employees",
"location",
"name"
]</code></pre>
<h3>shell脚本静态检查工具 shellcheck</h3>
<pre><code class="js">//https://github.com/koalaman/shellcheck
apt-get install shellcheck
shellcheck test.sh</code></pre>
<h3>多线程下载工具 axel</h3>
<pre><code class="js">// axel.alioth.debian.org/
sudo apt-get install axel
axel -n 10 -a <url>
axel -n 20 http://centos.ustc.edu.cn/centos/7/isos/x86_64/CentOS-7-x86_64-Minimal-1511.iso</code></pre>
<h3>命令行请求工具 httpie</h3>
<pre><code class="js">//https://httpie.org/ https://github.com/jakubroztocil/httpie
pip install --upgrade httpie
http PUT example.org X-API-Token:123 name=John
http -f POST example.org hello=World
http example.org/file > file
http httpbin.org/post -- -name-starting-with-dash=foo -Unusual-Header:bar
POST /post HTTP/1.1
-Unusual-Header: bar
Content-Type: application/json
{
"-name-starting-with-dash": "value"
}</code></pre>
<h3>命令行文档 tldr</h3>
<pre><code class="js">// https://github.com/tldr-pages/tldr
npm install -g tldr
$ tldr curl
Cache is out of date, you should run "tldr --update"
curl
Transfers data from or to a server.
Supports most protocols including HTTP, FTP, POP.
- Download a URL to a file:
curl "URL" -o filename
- Send form-encoded data:
curl --data name=bob http://localhost/form
- Send JSON data:
curl -X POST -H "Content-Type: application/json" -d '{"name":"bob"}' http://
localhost/login
- Specify an HTTP method:
curl -X DELETE http://localhost/item/123
- Head request:
curl --head http://localhost
- Include an extra header:
curl -H "X-MyHeader: 123" http://localhost
- Pass a user name and password for server authentication:
curl -u myusername:mypassword http://localhost</code></pre>
<h3>命令行提示工具 cheat</h3>
<pre><code class="js">//https://github.com/chrisallenlane/cheat
pip install cheat
cheat tar
# To extract an uncompressed archive:
tar -xvf '/path/to/foo.tar'
# To extract a .gz archive:
tar -xzvf '/path/to/foo.tgz'
# To create a .gz archive:
tar -czvf '/path/to/foo.tgz' '/path/to/foo/'
# To extract a .bz2 archive:
tar -xjvf '/path/to/foo.tgz'
# To create a .bz2 archive:
tar -cjvf '/path/to/foo.tgz' '/path/to/foo/'</code></pre>
<h3>后台运行和管理进程 pm2 同python的supervisoerd</h3>
<pre><code class="js">//http://pm2.keymetrics.io/
npm install pm2 -g
pm2 list</code></pre>
<h3>在命令行实时监控 Nginx 的神器 ngxtop</h3>
<pre><code class="js">//https://linux.cn/article-3205-1.html
pip install ngxtop
ngxtop -n 20
ngxtop info</code></pre>
<h3>python代码格式规范化工具 yapf</h3>
<pre><code class="js">//https://github.com/google/yapf
pip install yapf
>>> from yapf.yapflib.yapf_api import FormatCode # reformat a string of code
>>> FormatCode("f ( a = 1, b = 2 )")
'f(a=1, b=2)\n'
</code></pre>
<h3>命令行下模糊搜索工具 fzf</h3>
<pre><code class="js">//https://github.com/junegunn/fzf
brew install fzf
find * -type f | fzf > selected</code></pre>
<h3>网易云音乐命令行版本 musicbox</h3>
<pre><code class="js">//https://github.com/darknessomi/musicbox
pip(3) install NetEase-MusicBox
$ git clone https://github.com/darknessomi/musicbox.git && cd musicbox
$ python(3) setup.py install</code></pre>
<h3>多线程下载工具 aria2</h3>
<pre><code class="js">//https://github.com/aria2/aria2
aria2c http://a/f.iso ftp://b/f.iso
aria2 下载百度云链接https://github.com/acgotaku/BaiduExporter
</code></pre>
<h3>比 python -m SimpleHTTPServer 更好的 http 服务器 http-server</h3>
<pre><code class="js">//https://github.com/indexzero/http-server
npm install http-server -g
http-server 8888
alias hs="source ~/.bash_profile && http-server -a $(ifconfig en0 | grep 'inet ' | cut -d ' ' -f 2)"
//浏览器打开http://localhost:8888</code></pre>
<h3>获取汉字拼音 pypinyin</h3>
<pre><code class="js">pip install pypinyin
$ pypinyin 有哪些命令行的软件堪称神器
yǒu něi xiē mìng lìng xíng de ruǎn jiàn kān chē</code></pre>
<h3>Nginx配置静态分析器</h3>
<pre><code class="js">https://github.com/yandex/gixy
pip install gixy
gixy /etc/nginx/nginx.conf</code></pre>
<h3>HTTP Prompt</h3>
<pre><code class="js">pip install http-prompt
pip install httpie
# No parameters initially
> httpie
http http://localhost
# Send a request with some overrided parameters
> post /api/v1 --form name=jane
# Current state remains intact
> httpie
http http://localhost</code></pre>
<p><img src="/img/bVQa9e?w=656&h=388" alt="clipboard.png" title="clipboard.png"></p>
<h3>node ppt</h3>
<pre><code class="js">https://github.com/ksky521/nodePPT
npm install -g nodeppt
执行 nodeppt start
访问 http://127.0.0.1:8080/
在线demo: http://js8.in/nodeppt/</code></pre>
<p><img src="/img/bVQbf0?w=707&h=294" alt="clipboard.png" title="clipboard.png"></p>
<h3>检查浏览器的兼容性</h3>
<pre><code class="js">npm install -g caniuse-cmd
$ caniuse flex
Flexible Box Layout Module √ 83.86% Θ 13.63% [W3C Candidate Recommendation]
Method of positioning elements in horizontal or vertical stacks. Support
includes the support for the all properties prefixed with `flex` as well as
`display: flex`, `display: inline-flex`, `align-content`, `align-items`,
`align-self`, `justify-content` and `order`. #CSS3
IE × 5.5+ Θ 10+ᵖ² Θ 11⁴
Edge √
Firefox Θ 2+ᵖ¹ Θ 22+³ √ 28+
Chrome Θ 4+ᵖ¹ √ 21+ᵖ √ 29+
Safari Θ 3.1+ᵖ¹ √ 6.1+ᵖ √ 9+
Opera × 9+ √ 12.1+ √ 15+ᵖ √ 17+
¹Only supports the [old
flexbox](http://www.w3.org/TR/2009/WD-css3-flexbox-20090723) specification
and does not support wrapping.
²Only supports the [2012
syntax](http://www.w3.org/TR/2012/WD-css3-flexbox-20120322/)
³Does not support flex-wrap, flex-flow or align-content properties
⁴Partial support is due to large amount of bugs present (see known issues)
ⓘ Most partial support refers to supporting an [older
version](http://www.w3.org/TR/2009/WD-css3-flexbox-20090723/) of the
specification or an [older
syntax](http://www.w3.org/TR/2012/WD-css3-flexbox-20120322/).</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=QOIOBeWq2mqfmdsVyZFC2g%3D%3D.thS8SJYHpSwPJXAbTgQNV2OoLA0NF9Ui3GT%2FrfH7cFCRvD8CY2lmld%2BBH10dtioV" rel="nofollow">命令行翻译工具</a></h3>
<pre><code class="js">npm install terminal-translate -g
//类似 npm install fanyi -g https://github.com/afc163/fanyi
$ tl great
~ great - [greɪt] 美[ɡret] 英[greɪt]
~ 伟大的
- n. 大师;大人物;伟人们
- adj. 伟大的,重大的;极好的,好的;主要的
1. Great
伟大的,Great,Great
2. Great Lakes
五大湖,五大湖,大湖区
3. Great Recession
经济大衰退,大衰退,大萧条
</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=m5KIM0SbGpct8c9eva%2FvoQ%3D%3D.iI7wi1y%2F4kXOy%2FYGF%2FLv%2Bg%3D%3D" rel="nofollow">短域名工具</a></h3>
<p><code>npm i -g u.nu</code></p>
<h3><a href="https://link.segmentfault.com/?enc=eoKK6ZZ2QUzh7HKpjCtkhQ%3D%3D.313EiaO72Ar%2BWbm0U5phkjk3DrSS618CgdYUzJvHuX5pEzmDVZKY5kDfl6L0Ijc%2B" rel="nofollow">图片识别</a></h3>
<pre><code class="js">npm install baidu-ocr-api -g
ocr --help
# 远程图片
ocr http://7pun4e.com1.z0.glb.clouddn.com/test.jpg
# 本地图片
ocr ./test.jpg</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=nfO%2BbKp9fcIy2gYHLEOllw%3D%3D.8BXuAEfuYefdTa6dLu%2FbLkrXuMaq5KGbQ5BcvETc2Ww%3D" rel="nofollow">文件比较</a></h3>
<pre><code class="js">npm install -g diffchecker
diffchecker file1.js file2.js
diffchecker --expires day file1.js file2.js</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=Vk4o%2FL8hMAX%2BjdWhIXZ3Bw%3D%3D.Rhf4jK%2BgD7NpDOv9xhJ5lUjp1HGTkwwuR23ooPcR5Xg%3D" rel="nofollow">分享文件</a></h3>
<pre><code class="js"># Uploading is easy using curl
$ curl --upload-file ./hello.txt https://transfer.sh/hello.txt
https://transfer.sh/66nb8/hello.txt
$ curl -H "Max-Downloads: 1" -H "Max-Days: 5" --upload-file ./hello.txt https://transfer.sh/hello.txt
https://transfer.sh/66nb8/hello.txt
# Download the file
$ curl https://transfer.sh/66nb8/hello.txt -o hello.txt</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=yBzMnPDaNH%2FoJ%2BEI3XR8KA%3D%3D.7fy4uK03dyQSYujdpitQ8yFqNnTCXPROqogOaWhk9OtzCvQ0rBSRrLfgjrimMfQl" rel="nofollow">send emails</a></h3>
<pre><code class="js">First, create a config.json with your SMTP settings:
{
"host": "smtp.foobar.net",
"port": 465,
"user": "noreply",
"pass": "foobar!"
}
Install the app and start it up to point at the config:
npm i mailit -g
mailit --config /path/to/config.json
And presto, a mail endpoint! Let's try it out:
curl --data "to=d@me.net&subject=hi&text=hey world" http://127.0.0.1:3000/email
</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=bOK6mJ2J6P0Rn9kwjH6AHw%3D%3D.U2lMYw%2BGw%2BgZPLfZUAHkvORhhvYaqlq5pc9O0tIFj5B0%2BpIb%2FRvj1GJyhyR8ZpUF" rel="nofollow">learnyoubash</a></h3>
<p><code>npm install -g bash-handbook</code></p>
<h3><a href="https://link.segmentfault.com/?enc=liJwnrbaMhSI7EeXBy3bUg%3D%3D.opOV896it%2FmOZGspoTKuRoWhdANm7krKqL%2B0z5KUPyVU%2FtDlmn311xHxt1es4PeXtVBiJfLDjBfz7bYjoTJnlw%3D%3D" rel="nofollow">网易云音乐下载器</a></h3>
<pre><code class="js">$ git clone https://github.com/codezjx/netease-cloud-music-dl.git
$ python setup.py install
$ ncm -s 123123
or
$ ncm -s http://music.163.com/#/song?id=123123</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=DuYLZzO%2FWeTL%2B%2FEJlq2ZsQ%3D%3D.K6pj5%2FMr8Z5nU7y25s5anbrJEDbyP1JTGbQVLghz2K%2FHXc7oy6MnvsBhxYeGQgpC" rel="nofollow">curl 统计分析 httpstat </a></h3>
<pre><code class="js">pip install httpstat
httpstat httpbin.org/get</code></pre>
<p><img src="/img/bVTKTY?w=865&h=521" alt="clipboard.png" title="clipboard.png"></p>
<h3><a href="https://link.segmentfault.com/?enc=fW7C4SPgK9j18pB711lNxw%3D%3D.CLJ7TWq0uesg2sQqdRmWHKFqeUIUpsnqCYgQGEER0BE%3D" rel="nofollow">清除多余 css</a></h3>
<pre><code class="js">//https://github.com/purifycss/purifycss
$ npm install -g purify-css
$ purifycss -h
purifycss <css> <content> [option]
Options:
-m, --min Minify CSS [boolean] [default: false]
-o, --out Filepath to write purified css to [string]
-i, --info Logs info on how much css was removed
[boolean] [default: false]
-r, --rejected Logs the CSS rules that were removed
[boolean] [default: false]
-w, --whitelist List of classes that should not be removed
[array] [default: []]
-h, --help Show help [boolean]
-v, --version Show version number [boolean]</code></pre>
<h3>http 请求工具</h3>
<pre><code class="js">pip install http
#验证代理ip有效性 将响应与真实IP进行对比,如果不一样就有效
$ http --proxy http://59.49.129.60:8998 http://ip.cip.cc
HTTP/1.1 200 OK
Connection: keep-alive
Content-Length: 13
Content-Type: text/plain; charset=utf-8
Date: Sat, 09 Sep 2017 01:06:40 GMT
P3P: CP='CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NO
I DSP COR'
Proxy-Connection: keep-alive
Server: nginx
Vary: Accept-Encoding
59.49.129.60
>>> pro={'http':'59.49.129.60:8998'}
>>>pro=requests.get('http://lab.crossincode.com/proxy/get/?num=35&head=https').json()['proxies']
>>> import requests as rq
>>> r=rq.get('http://ip.cip.cc',proxies=pro)
>>> r.text
'59.49.129.60\n'</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=fB%2Bm5f%2B%2F7UVdChJphwuvHw%3D%3D.VQ77yr1%2FZOkbtV%2Bct86bJDWTeKILRtkmwcqayy7tljg%2BeRgt31CJGX5%2BIHkoBAsr" rel="nofollow">手机号码归属地查询工具</a></h3>
<pre><code class="js">npm install -g cellocate
cellocate 13888888888
13888888888
云南 昆明 移动</code></pre>
<h3><a href="https://segmentfault.com/a/1190000011692777">搭建简易静态文件http服务器</a></h3>
<pre><code class="js">python3 -m http.server port
npm install http-server -g
npm install -g serve
npm install -g anywhere
npm -g install puer
php -S localhost:9999</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=hR0%2BPJ75yEuZh29WBauuNA%3D%3D.fcC6cxss9vEPL%2BdBwJ1%2BeIPAA%2BV4IrTht9TvYjvROvM0asGThYh7dmdImg1ndNh4" rel="nofollow">命令行单词管理工具 iSearch</a></h3>
<pre><code class="js">pip install iSearch
s sun
sun 不在数据库中,从有道词典查询
sun /sʌn/
N-SING The sun is the ball of fire in the sky that the Earth goes around, and that gives us heat and light. 太阳
例:The sun was now high in the southern sky. 太阳当时正高挂在南面天空上。
例:The sun came out, briefly. 太阳出来了,时间很短。 </code></pre>
<h3><a href="https://link.segmentfault.com/?enc=L0VgW9RIcJFPTHLAjWIvyQ%3D%3D.l0e5PRCNFfnQwPotZQFLE9eVLpLGxnixuaIa9mrhRKLBPWDALr5qXBQePY4zHXJl" rel="nofollow">网页截图</a></h3>
<pre><code class="js">npm install capteer -g
capteer <url> [filename] [options]</code></pre>
<p><a href="https://link.segmentfault.com/?enc=7gAI3ORNIVyI0tZcN4Nmbg%3D%3D.UMbv3EA8MsbJYf16FoJf0nOULZfGAZeOEbgLi6wh%2FlpfwS7gDczpH0DaaQTBy%2FU1" rel="nofollow">更多</a><br><a href="https://link.segmentfault.com/?enc=4FbAyXb7h8bBHWXXuPJvLA%3D%3D.nYxP9xjdEIpMJpVuREyiOrh1ZMhRcja4ZO5PLXWUY30%3D" rel="nofollow">用爽截图</a><br><a href="https://link.segmentfault.com/?enc=G1Hr%2F%2FOL6siM4OnwXKwXhg%3D%3D.qwhv%2B1V04TZRqV6Sy6iyjIcjG1N9Qxv73M2NwqA8XT2xIUNQAJhfLcHEYfTwjXV%2B" rel="nofollow">命令行工具</a><br>公众号:苏生不惑</p>
<p><img src="/img/bVOYWr?w=425&h=433" alt="clipboard.png" title="clipboard.png"></p>
php上传图片到微博图床
https://segmentfault.com/a/1190000008490501
2017-02-26T19:25:15+08:00
2017-02-26T19:25:15+08:00
苏生不惑
https://segmentfault.com/u/sushengbuhuo
3
<p>微博是个好图床,上传后就可以通过一个url来访问了。今天就用php来上传图片到微博,这也是来自<a href="https://segmentfault.com/q/1010000008250059">sf的一个问题</a>, 里面还提到一个python版本.</p>
<p>有2种方式实现上传图片:</p>
<blockquote>
<p>如果要用 <a href="https://link.segmentfault.com/?enc=epS7hT3yyHh5J%2FIf9YRIYA%3D%3D.JcbHADtk9JllJApKLXZrFGt%2F7ZGGfF2Lut4f8SX4fe1Vf8qQNJrUp4Jr9DQX6Ynu%2BSrFRvqF3gvcNV0TkT8IwlPHzLO2q0oKWdAzP3XYyjUawbBVNn9Qt0TaX1E4OpwZtLt37K8IXQR6V3oMqt4h6DxtiVQsnx3qY%2BKg6dGpIvjnjgURBY0kcSplT00JJheCpYg1gsOxfuPI9YE%2BcLYocQbQgVNuUIZrnb2VQGOs7ho%3D" rel="nofollow">http://picupload.service.weib...</a> 这个 URL 的话POST 参数必须是 b64_data,值为经过 base64 编码后的字符串。</p>
<p>如果要使用 pic1 参数的话,则要用 multipart 方式进行上传,且 URL 中必须包含 cb 参数,cb 参数的值为 <a href="https://link.segmentfault.com/?enc=V1SQUh9tXM0%2Bd4b%2FaC6zVA%3D%3D.mnifO8%2Bp7uVm4QBSWI32EUVxeOAVilSNEvyvlG2YoDN676HnYTlRgarlC6GTDXKGzZlPc3DkOcDNLBIBVCcMcjTO4gYqlZucA7Al5X8K80c%3D" rel="nofollow">http://weibo.com/aj/static/up...</a> 加(js)时间戳</p>
</blockquote>
<p>以下为php实现,感谢这个问题下@consatan 的回复,这里做个总结。</p>
<h3>使用base64上传</h3>
<pre><code class="js">$cookie = 'your cookie';//登录微博network获取
$ch = curl_init('http://picupload.service.weibo.com/interface/pic_upload.php'
. '?mime=image%2Fjpeg&data=base64&url=0&markpos=1&logo=&nick=0&marks=1&app=miniblog');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_VERBOSE => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ["Cookie: $cookie"],
CURLOPT_POSTFIELDS => ['b64_data' => base64_encode(file_get_contents('./sf.jpg'))],
]);
$res = curl_exec($ch);
curl_close($ch);
print_r($res);
/*
{"code":"A00006","data":{"count":1,"data":"eyJ1aWQiOjMyNDMwMjYyMzcsImFwcCI6Im1pbmlibG9nIiwiY291bnQiOjEsInRpbWUiOjE0ODc3NDIyMDYuMzIxLCJwaWNzIjp7InBpY18xIjp7IndpZHRoIjo1MTAsInNpemUiOjUyOTMzLCJyZXQiOjEsImhlaWdodCI6MzMwLCJuYW1lIjoicGljXzEiLCJwaWQiOiJjMTRjYTczZGx5MWZjejcxejNyN25qMjBlNjA5NnE1ZiJ9fX0=","pics":{"pic_1":{"width":510,"size":52933,"ret":1,"height":330,"name":"pic_1","pid":"c14ca73dly1fcz71z3r7nj20e6096q5f"}}}}
$data=base64_decode($res['data']['data'])
{"uid":3243026237,"app":"miniblog","count":1,"time":1487742206.321,"pics":{"pic_1":{"width":510,"size":52933,"ret":1,"height":330,"name":"pic_1","pid":"c14ca73dly1fcz71z3r7nj20e6096q5f"}}}
*/
//c14ca73dly1fcz71z3r7nj20e6096q5f就是微博图片id,访问http://ww3.sinaimg.cn/large/c14ca73dly1fcz39h7mo3j20e6096q5f即可打开图片,这里我上传的是sf的广告图。
</code></pre>
<p><img src="/img/remote/1460000008490504?w=510&h=330" alt="sf" title="sf"></p>
<h3>multipart 方式上传</h3>
<pre><code class="js">$cookie = 'your cookie';//登录微博network获取
$post_data['pic1']=new CURLFile(realpath('sf.jpg'));
$time=substr(strval(microtime(true) * 1000), 0, 13) . 1;
$url="http://picupload.service.weibo.com/interface/pic_upload.php?mime=image%2Fjpeg&data=base64&url=0&markpos=1&logo=&nick=0&marks=1&app=miniblog&cb=http://weibo.com/aj/static/upimgback.html?_wv=5&callback=STK_ijax_".time();
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_COOKIE, $cookie);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//multipart 方式上传需要注意传递的参数是数组,不是字符串
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
//curl_setopt($ch, CURLOPT_HEADER, 1);
// curl_setopt($ch, CURLOPT_NOBODY, 0);
$output = curl_exec($ch);
$rinfo=curl_getinfo($ch);
print_r($output);
curl_close($ch);
/*
{"code":"A20001","data":{"count":2,"data":"eyJ1aWQiOjMyNDMwMjYyMzcsImFwcCI6Im1pbmlibG9nIiwiY291bnQiOjIsInRpbWUiOjE0ODc3MzQzMzUuNDU3LCJwaWNzIjp7InBpY18yIjp7InJldCI6LTIsIm5hbWUiOiJwaWNfMiJ9LCJwaWNfMSI6eyJ3aWR0aCI6NTEwLCJzaXplIjo1MjkzMywicmV0IjoxLCJoZWlnaHQiOjMzMCwibmFtZSI6InBpY18xIiwicGlkIjoiYzE0Y2E3M2RseTFmY3ozOWg3bW8zajIwZTYwOTZxNWYifX19","pics":{"pic_2":{"ret":-2,"name":"pic_2"},"pic_1":{"width":510,"size":52933,"ret":1,"height":330,"name":"pic_1","pid":"c14ca73dly1fcz39h7mo3j20e6096q5f"}}}}
*/
//从结果中获取pid即可,这里发现上传同一张图片返回的pid是相同的,看来微博有处理,也许是比较文件的md5.</code></pre>
<p>这里需要注意php不同版本上传图片的处理,<a href="https://segmentfault.com/a/1190000000725185">参考这个链接</a> ,传统上,PHP的cURL支持通过在数组数据中,使用“@+文件全路径”的语法附加文件,供cURL读取上传,但PHP从5.5开始引入了新的CURLFile类用来指向文件,所以做个处理:</p>
<pre><code class="js">if (class_exists('\CURLFile')) {
$field = array('fieldname' => new \CURLFile(realpath($filepath)));
} else {
$field = array('fieldname' => '@' . realpath($filepath));
}</code></pre>
jquery记录
https://segmentfault.com/a/1190000007833494
2016-12-17T11:24:52+08:00
2016-12-17T11:24:52+08:00
苏生不惑
https://segmentfault.com/u/sushengbuhuo
0
<h3><a href="https://segmentfault.com/q/1010000007829415">获取form的所有的表单元素</a></h3>
<p>document.forms['eg'].elements;<br> $.map($('[name=eg]').serializeArray(), function(item, index){</p>
<pre><code>return $('[name='+item['name']+']');</code></pre>
<p>});</p>
<h3>replace第一个参数拼接变量</h3>
<p>replace(new RegExp(this.value, 'g'),'<b>'+this.value+'</b>');</p>
<h3><a href="https://segmentfault.com/q/1010000007825724">函数this</a></h3>
<p>setInterval(_this.autoPlay.bind(_this),3000);<br>setInterval("_this.autoPlay()",3000);如果第一个参数是字符串的话,类似eval</p>
<p>function Pig() {};<br>Pig.prototype={</p>
<pre><code>init:function () {},
move:function () {},
render:function(){
this.move();
console.log(this)
}</code></pre>
<p>}</p>
<p>var pigPlayer=new Pig();</p>
<pre><code> setInterval(pigPlayer.render.bind(pigPlayer),1000);
setTimeout(function(){pigPlayer.render()},1000)</code></pre>
<h3><a href="https://segmentfault.com/q/1010000007820045">获取URL中的参数</a></h3>
<pre><code class="php">var urlParams;
(window.onpopstate = function() {
var match,
pl = /\+/g,
search = /([^&=]+)=?([^&]*)/g,
decode = function(s) {
return decodeURIComponent(s.replace(pl, " "));
},
query = window.location.search.substring(1);
urlParams = {};
while (match = search.exec(query))
urlParams[decode(match[1])] = decode(match[2]);
})();
var a =document.createElement('a');
a.href='http://www.cnblogs.com/season-huang/index?param=yes&article=1';
query = a.search.substring(1);
urlParams = {};
arr.map(function(i){
urlParams[i.split('=')[0]]=i.split('=')[1]
});
console.log(urlParams)
//Object {param: "yes", article: "1"}
var paramsString = "q=URLUtils.searchParams&topic=api"
var searchParams = new URLSearchParams(paramsString);
searchParams.get('q')</code></pre>
<h3><a href="https://segmentfault.com/q/1010000007828882">闭包</a></h3>
<pre><code class="php">var apples = ["apple1", "apple2", "apple3"];
for (var i = 0, funs = []; i < 3;i ++){
funs[i] = function(){
console.log(apples[i]);
}
}
funs[0]();
funs[1]();
funs[2]();//undefined
var apples = ["apple1", "apple2", "apple3"];
for (var i = 0, funs = []; i < 3;i ++){
funs[i] = (function(x){
return function(){
console.log(apples[x]);
}
})(i);
}
funs[0]();
funs[1]();
funs[2]();//apple3</code></pre>
<h3><a href="https://segmentfault.com/q/1010000007828822">钱换啤酒</a></h3>
<p>function computed(money) {</p>
<pre><code>var num = parseFloat(money) / 2;
var pingzi = num, gaizi = num;
var total = num;
reComputed();
function reComputed() {
if (pingzi < 2 && gaizi < 4) {
return;
}
if (pingzi >= 2) {
var beishu = Math.floor(pingzi / 2);
pingzi = pingzi - beishu * 2 + Math.floor(pingzi / 2);
gaizi = gaizi + beishu;
total = total + beishu;
} else {
var beishu_1 = Math.floor(gaizi / 4);
gaizi = gaizi - beishu_1 * 4 + Math.floor(gaizi / 4);
pingzi = pingzi + beishu_1;
total = total + beishu_1;
}
reComputed();
}
return total;</code></pre>
<p>}</p>
<h3><a href="https://link.segmentfault.com/?enc=o60%2FTR8leNm3MGJfhHZhUw%3D%3D.IVULybk2LHFbBCghVmekx07ka4eILNsAFJoUsZa5NAYwGE1%2F88cPsAKFHy6ILDlz" rel="nofollow">javascript黑点</a></h3>
<p>[<img src="/img/bVG2DS?w=573&h=420" alt="clipboard.png" title="clipboard.png"></p>
<p><img src="/img/bVG2DT?w=484&h=266" alt="clipboard.png" title="clipboard.png"></p>
<p><img src="/img/bVG2DT?w=484&h=266" alt="clipboard.png" title="clipboard.png"></p>
<pre><code class="js">parseInt(0.00000008)//8
parseInt(0.000008)//0
对应python
>>> 0.2.hex()
'0x1.999999999999ap-3'
>>> (0.8 - 0.6).hex()
'0x1.999999999999cp-3'
>>> 0.1.hex()
'0x1.999999999999ap-4'
>>> (0.8 - 0.7).hex()
'0x1.99999999999a0p-4'
>>> (0.2 - 0.1).hex()
'0x1.999999999999ap-4'
> 0 >= null
true
> 0 <= null
true
> 0 == null
false
> 0 === null
false
> [] == []
false
> [] === []
false</code></pre>
css记录收集
https://segmentfault.com/a/1190000007680505
2016-12-03T10:22:46+08:00
2016-12-03T10:22:46+08:00
苏生不惑
https://segmentfault.com/u/sushengbuhuo
0
<h3><a href="https://link.segmentfault.com/?enc=vK6h4JgdrhvpWXWleKDI3Q%3D%3D.nPHtx1T9lTdwjXnL6ESrg7pF%2Bxh5VB63%2BC2UPe7Jz8thSwkhzqcj1%2FXvTdz56fmz" rel="nofollow">让一个块级元素在某区域内上下左右居中</a></h3>
<pre><code class="php"><div class="container">
<div class="box"></div>
</div>
<style>
.container {
border: 1px solid #000;
width: 300px;
height: 300px;
position: relative;
}
.box {
border: 1px solid #000;
width: 50px;
height: 50px;
/* magic below */
position: absolute;
margin: auto;
left: 0;
right: 0;
top: 0;
bottom: 0;
/* magic end */
}
</style></code></pre>
<h3>文字模糊效果</h3>
<p>*{</p>
<pre><code>color: transparent;
text-shadow: #111 0 0 5px;</code></pre>
<p>}</p>
<h3><a href="https://link.segmentfault.com/?enc=s1SBxcYaoCudJZFTI18OKQ%3D%3D.1li%2FOABSF5EI%2B5KpRcRYzLQqB%2B1fAZ1bIxQ%2Bzv1w8iG6M97J9uIg2dvfI5Sr%2Fn99" rel="nofollow">实时编辑CSS</a></h3>
<p><html></p>
<pre><code><body>
<style style="display:block" contentEditable>
body { color: blue }
</style>
</body></code></pre>
<p></html></p>
linux及git记录
https://segmentfault.com/a/1190000007535708
2016-11-19T22:38:27+08:00
2016-11-19T22:38:27+08:00
苏生不惑
https://segmentfault.com/u/sushengbuhuo
0
<h3><a href="https://link.segmentfault.com/?enc=vHSPYNQ1REyE2aTDEcD5lA%3D%3D.rksONwwKdShHjPgBP34nTp%2B4rRkJZ8iaO3flgmzcGVrd630I1ixA4TFyxO%2BLXUlX" rel="nofollow">git撤销</a></h3>
<p>Git Add了一个错误文件<br>git reset <file> #撤销指定的文件<br>git reset #撤销所有的文件 只撤销commit操作,保留文件Git Commit了一个错误文件 <br>git reset HEAD~1 撤销commit操作,删除变化<br>git reset --hard HEAD~1 <br>删除本地和远程的test分支 <br>git push origin --delete test<br>git checkout master<br>git branch -d test<br>git branch -D test 如果有未提交的文件</p>
<h3><a href="https://link.segmentfault.com/?enc=G678%2F1jzeiMR2MDJ24QydA%3D%3D.eoiIT2F457lqIryNxcxVrf1zQcHfaQcHsfZ0dz%2B5f7abSN%2BuU2H8VPbqGsOUNczkafBETW9iU9YNo0a5mtubjxmvsT%2B02QJx6%2BgrVjIVR%2Bs%3D" rel="nofollow">Redis 性能分析与优化</a></h3>
<pre><code class="js">redis-cli -h <host> -p <port> -n <db> --bigkeys#得到的 value 占用空间最大的 key 值
slowlog 这个子命令可以获取当前的这些记录 127.0.0.1:6379> slowlog get 3</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=fME1%2FIHiRzAeTxZ%2ByKXW9A%3D%3D.HyK2B5WVtHEvvPCcekfupsHwq3%2FJJlDLt3%2BnZjlWYEH2qtNCt2HaLzTGcWU3kC2qPatZXzwihLGdLjW7xOGrsg%3D%3D" rel="nofollow">随机数</a></h3>
<p><code>echo $RANDOM</code><br><code>od -An -N2 -i /dev/random</code></p>
<h3><a href="https://link.segmentfault.com/?enc=dVrW45uBI6cvZGXYxdIIFQ%3D%3D.5ZUNhaoXJ9dbb9f8X1PsjBDFSrRDaxmpbCvP%2FD7P64vW8YO9swvV4DyykLxHR7gHwnQxg7zduYCj0DjJEbGdDg%3D%3D" rel="nofollow">开源 OCR</a></h3>
<pre><code class="js">bash > tesseract --list-langs
List of available languages (17):
math
chi
chi_sim
eng
tesseract paper.png paper -l chi_sim
tesseract input.png output -l eng</code></pre>
<h3>清空Github上某个文件的历史</h3>
<pre><code class="php">git filter-branch --force --index-filter 'git rm --cached --ignore-unmatch app/img/*' --prune-empty --tag-name-filter cat -- --all
git push origin master --force
rm -rf .git/refs/original/
git reflog expire --expire=now --all
git gc --prune=now
git gc --aggressive --prune=now</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=8ibuV7I%2Fn8%2B7tBhN5Z9zJw%3D%3D.QRqUTt4XY4gO%2FBrSSMVx7Jc957KkzofMVl9wJVwfDyla3jJDc13qatF5zsfwDt4eNI%2FpVRXff%2FYugAkBd7S6tg%3D%3D" rel="nofollow">使用 iconv 对大文件编码转换 GB2312 - UTF8</a></h3>
<p>iconv -f gb2312 -t utf-8//IGNORE av-ed2k-合集.data > 日语教学.txt<br>wc -l 日语教学.txt av-ed2k-合集.data</p>
<h3><a href="https://link.segmentfault.com/?enc=YEh8%2FAo%2FW9Z%2B9ce559tIBQ%3D%3D.OLywn7bfByzQHsSDtB6vQmSbtDvO%2BAbtptAcVSxrX4lyNIxxBEtXsL9uXApoQEGQJbAJyTFyZoO69HgWkFFvWA%3D%3D" rel="nofollow">Nginx 上限制单 IP 单位时间的请求数,以及单 IP 的并发连接数</a></h3>
<p>http {</p>
<pre><code>limit_req_zone $binary_remote_addr zone=one:10m rate=8r/s;
server {
location /search/ {
limit_req zone=one burst=5;
}</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=hoI0aqjYnSAXEeW3DQcTMQ%3D%3D.dNzmflx0beHyN48yKJLwIV2mW%2FZRtTxGgJ6D39phORTZwXw105bKP3Xh3nNeqrVIP4R6yOFuoAGF3UqYHrGs6A%3D%3D" rel="nofollow">使用 Nginx 限制页面访问权限</a></h3>
<pre><code class="php">sudo apt-get install apache2-utils
sudo htpasswd -c /etc/nginx/.htpasswd myusername
server {
listen 80;
server_name ip_address;
location /backend {
root /var/www/sunzhongwei.com;
index index.html index.htm;
auth_basic "Restricted";
auth_basic_user_file /etc/nginx/.htpasswd;
}
}
sudo /etc/init.d/nginx reload
</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=5YONYcSqMbELyRbYvwAT0A%3D%3D.pfu2kTUs1vxDbvSYA9wOrHS9jjNcZpyOmmLWd0%2FDc301fjhN6RblJl1RpX8%2BXFhQjwmlfn6J1QLxiOPHDhY5U4e3%2FnjR9x0aMUVZ6u%2FVLZg%3D" rel="nofollow">命令行登陆github</a></h3>
<p>ssh-keygen -t rsa -C "邮件"<br>Generating public/private rsa key pair.<br>Enter file in which to save the key (/Users/MZero/.ssh/id_rsa):</p>
<p>登陆github。点击右上角的 Account Settings—>SSH and GPG keys —> new SSH key<br>$ ssh -T git@github.com<br>若有You’ve successfully authenticated提示,说明成功了</p>
<h3>git pull/push项目的时候总是提示要输入用户名密码的解决方案</h3>
<p>git config --global credential.helper store</p>
<h3><a href="https://link.segmentfault.com/?enc=qgA1cNHLNz%2FMg5eXP5IeTg%3D%3D.BnbJ5%2Brmw2q0px0GpYghMZ%2BsbrlN3eUEqlixjxDL337wdHD3PRMswrBD7RYDzWBXpm577F%2BhiHU%2FS9DmExpvsQ%3D%3D" rel="nofollow">服务器设置允许mysql远程登录</a></h3>
<p>vi /etc/sysconfig/iptables</p>
<p>-A INPUT -m state --state NEW -m tcp -p tcp --dport 3306 -j ACCEPT<br>service iptables restart<br>grant all on aaa.* to "root"@xx.yy.zz.cc identified by "123";<br>flush privileges;<br>grant all on aaa.* to "root"@"%" identified by "123";</p>
<h3><a href="https://link.segmentfault.com/?enc=%2FBT7ZVx70IcJeoGWOeM6ww%3D%3D.Xuij81tsRuATdghoiVkk1%2B13PeKZ7dNgcsQZIy%2F7MDVIxvzdJfkEyfplG%2FiBW3dxITA0MJ3zm35tSdywAFibwA%3D%3D" rel="nofollow">ssh 配置秘钥登录</a></h3>
<p>ssh-keygen -t rsa -C "you@homestead"</p>
<p>$ sudo vim /etc/ssh/sshd_config<br>RSAAuthentication yes<br>PubkeyAuthentication yes<br>AuthorizeKeyFile ~/.ssh/authorized_keys<br>service sshd restart<br>将公钥文件的内容追加到 ~/.ssh/authorized_keys 文件中,并且将文件权限置成 600<br>chmod 600 ~/.ssh/authorized_keys</p>
<p>$ vim .bash_profile<br>alias c14='ssh [username]@[server_ip] (-i ~/.ssh/[私钥文件])'<br>$ source .bash_profile<br>$ c14</p>
<h3><a href="https://link.segmentfault.com/?enc=r3Oyi6yCQDh8FsMM%2Fd0hYQ%3D%3D.XoCW9E%2F1hjOArxLvc9gZ6YQMCmkLx2hWwaFSbV0tRzz7uKi%2FhN7H7Wfzes3MrhGZKY47GsyILbh1fOdftOqXjg%3D%3D" rel="nofollow">Nginx 报 502 的解决思路</a></h3>
<p>nginx报错,查看nginx日志排错<br>nginx报502 bad gate way一般是因为没有配置好php-fpm<br>修改nginx或者php-fpm配置文件之后重启生效</p>
<h3><a href="https://link.segmentfault.com/?enc=yu5dwUOM82MSOA03ykfT7A%3D%3D.29MiCetJ98riliRCVoF%2BbywXaKhEmQJa9JU6iPSK%2BuNmQf%2FBLsffpltghYiD2dlBBjTEHlx5WFVpOKz1a0ZmgA%3D%3D" rel="nofollow">nginx 添加 https 和 http2 模块支持</a></h3>
<p>curl <a href="https://link.segmentfault.com/?enc=frRUCr73HnFw%2BF5jZJpdZw%3D%3D.iXRe2uj4zEl5MBWDdoZDcBDq2tdSLfVApeQ4qg%2FPWJgyStExfvxsoeSkgVupOiax" rel="nofollow">https://nginx.org/download/ng...</a> |\<br> tar xzf - && cd nginx-* # get latest nginx & extract it<br>./configure [old_config_arguments] --with-http_ssl_module --with-http_v2_module # 前面 [old_config_arguments] 可以从 nginx -V 里 copy<br>make<br>sudo make install<br>listen 443 ssl http2;<br>ssl_certificate /home/brook/ssl/chained.pem;<br>ssl_certificate_key /home/brook/ssl/domain.key;<br>ssl_dhparam /home/brook/ssl/dhparams.pem;<br>ssl_ciphers EECDH+CHACHA20:EECDH+CHACHA20-draft:EECDH+AES128:RSA+AES128:EECDH+AES256:RSA+AES256:EECDH+3DES:RSA+ 3DES:!MD5;<br>ssl_prefer_server_ciphers on;<br>ssl_protocols TLSv1 TLSv1.1 TLSv1.2;<br>ssl_session_cache shared:SSL:50m;<br>ssl_session_timeout 1d;<br>ssl_session_tickets on;<br>add_header Strict-Transport-Security max-age=31536000;<br>service reload nginx</p>
<h3><a href="https://link.segmentfault.com/?enc=A7Ownt%2FOMcfO5Ev3lKOQ9A%3D%3D.nRn0lpVcTtBq5EDh5MZLNVNRT5D6qnjskXEXuiyq%2BXALHfE0ZPJcuoAigKzpKQrATM1bEf9mSYPhfiVAxfHZT%2F6O9hghVfIM6wbssgxmz0I%3D" rel="nofollow">pphpmyadmin 缺少 mcrypt 扩展</a></h3>
<p>sudo apt-get install php-mcrypt libmcrypt libmcrypt-devel<br>sudo ln -s /etc/php5/mods-available/mcrypt.ini 20-mcrypt.ini<br>sudo service apache2 restart</p>
<h3><a href="https://link.segmentfault.com/?enc=d6EjQG2NquLBd59EcNuBnw%3D%3D.oHjByy3Ssjmga%2FHqHOZTwu8di72AnVF17QKMPW68ihh3gBMGsOy5D3%2Fqd20mxn7z" rel="nofollow">curl命令查看请求响应时间方法</a></h3>
<p>curl -o /dev/null -s -w %{time_namelookup}::%{time_connect}::%{time_starttransfer}::%{time_total}::%{speed_download}"n" <a href="https://link.segmentfault.com/?enc=H8fkpEGs5KlOKIIHRk0lBQ%3D%3D.%2BlPhAd%2BoY5RHcrhIoXfFAiyq82QJFj2DV5iJRxiAu4o%3D" rel="nofollow">http://www.36nu.com</a> </p>
<p>0.014::0.015::0.018::0.019::1516256.00</p>
<h3><a href="https://link.segmentfault.com/?enc=Q7rmAGnU1d0BO9YCUZQWCw%3D%3D.8BAh9I8XWNJlBk8iMlrWr5C58NsMiy7KcsWuxNrQe1vNsZCSHMLdjCF588FweToD" rel="nofollow">用github来展示你的前端页面</a></h3>
<p>创建项目新建gh-pages分支 通过 <a href="https://link.segmentfault.com/?enc=rOxsijvdwSYWN9N9W5%2Fuew%3D%3D.%2BZIofTw1PannysGp0vIGLpYfuHVGSK0r6r25ouHz3e%2FQGVimOAE8ZE3hjN5H%2FuhCAHvVCdKk9TY%2BjoO52UkSaA%3D%3D" rel="nofollow">http://(user_name|org_name).g...</a> 访问<br>一种更加简便的方式来实现:将代码上传至仓库后在settings里配置下GitHub Pages为你想展示的分支就行了</p>
<h3><a href="https://link.segmentfault.com/?enc=xbkkZFPkj0a5sqhUImPzcQ%3D%3D.oN4%2FDjnpOSFV%2Fq9swK%2Fib884opOjFmNE9Yid6Oo6igfEPn9K5yYDjNgO3pGuLOcOs1TJutLCv3v1EmqDj4QcRJFUDI%2FyAWfnwE5QouXkaF4%3D" rel="nofollow">pull request</a></h3>
<p>git clone 自己fork的project <br>然后添加一个上游地址git remote add upstream <br>git remote -v查看自己和fork来的地址 <br>git pull upstream master <br>增加分支 git checkout -b newbranch<br>git pull upstream master <br>再git rebase master将改动代码放在master前面 <br>git push origin newbranch </p>
<p><img src="/img/bVF41m?w=346&h=138" alt="clipboard.png" title="clipboard.png"></p>
<h3>代理ip</h3>
<p>curl <a href="https://link.segmentfault.com/?enc=QWnYyPe0wrS4eoAC%2B5ZGbg%3D%3D.zbWltDJv594wmmF%2FYdl0eTcx1w6YuhH3iizO4qPVz3E%3D" rel="nofollow">http://ip.chinaz.com/getip.aspx</a> -x '<a href="https://link.segmentfault.com/?enc=9wdcvrBB87Zexgh7k4oTtQ%3D%3D.y6F97e9OfK0QsdROmy7ANSKHkdsn4%2BgMvYWACIL65aM%3D" rel="nofollow">http://120.52.72.56:80</a>' <br>{ip:'120.52.72.56',address:'北京市 联通云 BGP 数据中心'}</p>
<h3>git add 如何只 add 某一行</h3>
<p>git add -p <a href="https://link.segmentfault.com/?enc=Myh11vxBvxaA7ijeAOXh3A%3D%3D.Xtjq13wP0LtpLzuU1Ddz8Ty7EJEgZQJErRphr%2FeZt3Xe0aGmLiB0AcNveCsJD%2BaSOPXC7fKYlcxLFGjEfunyrgHXjspJCpcF%2BgMwYDqoGMlqr%2F0SOkD8tCNYE4Oju9rr" rel="nofollow">http://stackoverflow.com/ques...</a></p>
<h3>判断linux是否被黑</h3>
<p>执行命令ls -l /usr/bin/ps看一下文件时间是不是最近更改过;对比下相同操作系统版本下的ps命令和这台的大小,如果不同,基本可以确定被入侵了</p>
<h3><a href="https://link.segmentfault.com/?enc=IVApG58E%2FGCr5FlPcNeLmw%3D%3D.1k73ZKVQmWTOgs4P6A3nu1McOoLOlRrHAHf1XlMxH8pErGk4i%2F78soosf0QEsG%2B8" rel="nofollow">格式化json</a></h3>
<p><code>echo '{"a": 1, "c": 3, "b": 2}' | python -m json.tool</code><br>删除文件中的空行<br>cat a.txt | sed -e '/^$/d'<br>常用命令history 1 -1 | awk '{a[$2]++}END{for(i in a){print a[i] " " i}}' | sort -rn | head<br>删除空文件/删除垃圾文件<br>find . -type f -size 0 -delete<br>find . -type f -name "a.out" -exec rm -rf {} ;</p>
<h3><a href="https://link.segmentfault.com/?enc=celraFNMBvNOM5Z1uYXVkg%3D%3D.zzjUomVWnF5sfL%2BwaWlAhUnIVyVOpT3vx1K9drSbZzUfXk2wtXBqbUInwQCjxwsHhlmL6mQhy%2FLUvk5uR4sVKg%3D%3D" rel="nofollow">Git中的username的设置</a></h3>
<p>git config --global user.name "spoock"<br>新的提交没有使用正确的name,很有可能是环境变量将username覆盖了</p>
<p>$ echo $GIT_COMMITTER_NAME<br>$ echo $GIT_AUTHOR_NAME</p>
<h3>chrome中的cookie存储位置</h3>
<p>地址栏中输入chrome://setings/password就可以查看浏览器上面保存的所有的密码了.<br>chrome还将这些cookie存在了本地的硬盘上面。目录在:<br>C:/Users/本地用户名/AppDate/Local/Google/Chrome/User Data/Default下的cookie文件。这个cookie文件是一个sqllite的文件</p>
<h3><a href="https://link.segmentfault.com/?enc=SJgMJfCbNC12PRw2RSyIRg%3D%3D.KjSORcP2kURqVdRkSC0IaIKAs1woBdIAJAq21vcfv1cGdVjiDymr85KbaZS3f7DM" rel="nofollow">正向代理与反向代理</a></h3>
<p>正向代理中proxy代理client来向一个server发起请求 而反向代理中proxy代理一个或者多个server接收clients的请求, server对于client来说是不可见的 代理:在客户这一端,替客户收发请求。<br>反向代理:在服务器机房这一端,替服务器收发请求,也就是说请求和响应都先经过反向代理。具有缓存、安全、负载均衡等作用。请求分发到多台服务器 正向代理代理客户端,反向代理代理服务器,一个是代理(v)客户端,为客户端收发请求,使真实客户端对服务器不可见。<br>一个是代理(v)服务器,为服务器收发请求,使真实服务器对客户端不可见。</p>
<h3><a href="https://link.segmentfault.com/?enc=RD6JR7z4QgrHKyoOFqFhbg%3D%3D.OfFvaLt1paelOdQRXK4h2RfCxHBW7vwiL%2F5DEzVrOprk6ZCHkIoo4UhzCdxqMtS%2BJ8dEamFCrurFjvOpLtzm5g%3D%3D" rel="nofollow">Nginx配置中的 root 与 alias 指令的区别</a></h3>
<p>location /i/ {</p>
<pre><code>root /data/w3;</code></pre>
<p>}<br>location /i/ {</p>
<pre><code>alias /data/w3/;</code></pre>
<p>}</p>
<p><img src="/img/bVGqPX?w=544&h=356" alt="clipboard.png" title="clipboard.png"></p>
<p><img src="/img/bVGqPY?w=544&h=356" alt="clipboard.png" title="clipboard.png"></p>
<p>alias 只能作用在location中,而root可以存在server、http和location中。</p>
<p>alias 后面必须要用 “/” 结束,否则会找不到文件,而 root 则对 ”/” 可有可无。</p>
<h3>在当前目录下所有文件中搜索字符串“windows”,并用“linux”替换之</h3>
<p>grep -rl 'windows' ./ | xargs sed -i 's/windows/linux/g'</p>
<h3>查看某个端口打开的文件(socket 连接)</h3>
<p>lsof -i :80</p>
<h3>列出用户打开的文件</h3>
<p>lsof -u root | more</p>
<h3>文件被哪些进程打开了</h3>
<p>lsof -a /var/lib/mysql/mysql/slow_log.CSV</p>
<h3><a href="https://link.segmentfault.com/?enc=bcnBS3NFoAeUhUfjO4A2aQ%3D%3D.7G6EhoB3aUvgwua951dkvPscwOrOCP%2FKfUsaGKJHvZshFl%2BAEkXrnRxrd%2FQLyBTc" rel="nofollow">Git push到多个远程库</a></h3>
<p>git remote add origin git@github.com:looly/hutool.git<br>git remote add osc git@git.oschina.net:loolly/hutool.git<br>git add .<br>git commit -m 'First commit'<br>git push origin master<br>git push osc master</p>
<h3><a href="https://link.segmentfault.com/?enc=o0iVtL8GHzZX66h9SzF1bg%3D%3D.LyMqoPLCPlhLCyIkGMHe4FTcWvmsuaTuH6xyMDNrbq7VirQ0ChVHxdNMkD%2Fa1Pn6QvzPgV9QZxjQE7xK6zbRHw%3D%3D" rel="nofollow">crontab的“坑”</a></h3>
<p>crontab的命令里面增加source /path/to/configfile<br>python task.py >> ~/debug.log 2>&1 crontab命令加上这个后缀(2>&1) 之后,我的debug.log 之中终于出现如下图所示的错误信息(sh: l: java not found)</p>
<h3>apt-get rpm</h3>
<p>Linux发行版主要有两派,Debian系和Redhat系</p>
<p>Debian系使用deb包,包管理是:apt-get</p>
<p>Redhat系使用rpm包,包管理是:rpm<br>Debian/Ubuntu:<br>二进制包 .deb<br>安装方式 dpkg -i xxx.deb<br>apt-get install xxxxx.deb<br>Centos:<br>二进制包 .rpm<br>安装方式apt-get update sudo apt-get install rpm rpm -ivh xxx.rpm<br>yum install xxxxx.rpm</p>
<h3><a href="https://segmentfault.com/q/1010000003834362">ffmpeg将视频转ts</a></h3>
<p>ffmpeg -i Wildlife.wmv -codec:v libx264 -codec:a mp3 -map 0 -f ssegment -segment_format mpegts -segment_list ./m3u8/index.m3u8 -segment_time 10 ./m3u8/’%03d.ts’</p>
php记录
https://segmentfault.com/a/1190000007207192
2016-10-18T22:06:16+08:00
2016-10-18T22:06:16+08:00
苏生不惑
https://segmentfault.com/u/sushengbuhuo
1
<h3>获取php pdo 执行的sql语句</h3>
<pre><code class="php">class MyPDOStatement extends PDOStatement
{
protected $_debugValues = null;
protected function __construct()
{
// need this empty construct()!
}
public function execute($values=array())
{
$this->_debugValues = $values;
try {
$t = parent::execute($values);
// maybe do some logging here?
} catch (PDOException $e) {
// maybe do some logging here?
throw $e;
}
return $t;
}
public function _debugQuery($replaced=true)
{
$q = $this->queryString;
if (!$replaced) {
return $q;
}
return preg_replace_callback('/:([0-9a-z_]+)/i', array($this, '_debugReplace'), $q);
}
protected function _debugReplace($m)
{
$v = $this->_debugValues[$m[1]];
if ($v === null) {
return "NULL";
}
if (!is_numeric($v)) {
$v = str_replace("'", "''", $v);
}
return "'". $v ."'";
}
}
// have a look at http://www.php.net/manual/en/pdo.constants.php
$options = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_STATEMENT_CLASS => array('MyPDOStatement', array()),
);
// create PDO with custom PDOStatement class
$pdo = new PDO($dsn, $username, $password, $options);
// prepare a query
$query = $pdo->prepare("INSERT INTO mytable (column1, column2, column3)
VALUES (:col1, :col2, :col3)");
// execute the prepared statement
$query->execute(array(
'col1' => "hello world",
'col2' => 47.11,
'col3' => null,
));
// output the query and the query with values inserted
//http://stackoverflow.com/questions/7716785/get-last-executed-query-in-php-pdo
var_dump( $query->queryString, $query->_debugQuery() );</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=dzxjvfIw%2Fo8%2FWKnAgNRMSg%3D%3D.zBaD0lWSc%2FG0zz3vY0NVarTAWbJhfvBbrsYolypuFLG1pG1IaFhEzsDgH87VRJ0%2B6Q3yR680v8QdfuHh4TgaVA%3D%3D" rel="nofollow">laravel Carbon</a></h3>
<pre><code class="php">composer require nesbot/carbon
use Carbon\Carbon;
\Carbon\Carbon::setLocale('zh');
echo Carbon::now()->toDateTimeString();
echo Carbon::parse('2016-10-15')->toDateTimeString();
Carbon::parse('+3 days')->toDateTimeString();
echo Carbon::parse('next wednesday')->toDateTimeString();
echo Carbon::now()->modify('+15 days');
$first = Carbon::create(2012, 9, 5, 23, 26, 11);
$second = Carbon::create(2012, 9, 5, 20, 26, 11, 'America/Vancouver');
var_dump($first->gt($second)); // bool(false)
var_dump(Carbon::create(2012, 9, 5, 3)->between($first, $second)); // bool(true)
$dt = Carbon::now();
$dt->isWeekday();
echo Carbon::now()->subDays(5)->diffForHumans(); // 5天前
echo $dt->diffForHumans($dt->copy()->addMonth()); // 1月前
echo Carbon::now()->subDays(24)->diffForHumans(); // 3周前</code></pre>
<h3>PHP 二进制安全</h3>
<pre><code class="php">//简单说就是传入的参数支持二进制数据,包括”\0″这种在 C 中表示字符串结束的字符
$string1 = "Hello";
$string2 = "Hello\x00Hello";
echo strcoll($string1, $string2); // 返回0, 由于是非二进制安全,误判为相等
echo strcmp($string1, $string2); // 返回负数</code></pre>
<h3>PHP 捕捉异常中断</h3>
<pre><code class="php">class IndexController extends Controller
{
/**
* 脚本执行是否完成
* @var bool
*/
protected $complete = false;
public function __construct()
{
register_shutdown_function([$this, 'shutdown']);
}
/**
* 异常处理
*/
public function shutdown()
{
if ($this->complete === false) {
dump('log'); //此处应该输出日志并进行异常处理操作
}
}
}</code></pre>
<h3>PHP如何批量生成手机号</h3>
<pre><code class="php">class Util {
private static $mobileSegment = [
'134', '135', '136', '137', '138', '139', '150', '151', '152', '157', '130', '131', '132', '155', '186', '133', '153', '189',
];
public function nextMobile()
{
$prefix = self::$mobileSegment[array_rand(self::$mobileSegment)];
$middle = mt_rand(2000, 9000);
$suffix = mt_rand(2000, 9000);
return $prefix . $middle . $suffix;
}
}
//匹配手机号的正则表达式 #^(13[0-9]|14[47]|15[0-35-9]|17[6-8]|18[0-9])([0-9]{8})$#
$arr = array(
130,131,132,133,134,135,136,137,138,139,
144,147,
150,151,152,153,155,156,157,158,159,
176,177,178,
180,181,182,183,184,185,186,187,188,189,
);
for($i = 0; $i < 10; $i++) {
$tmp[] = $arr[array_rand($arr)].' '.mt_rand(1000,9999).' '.mt_rand(1000,9999);
}
var_export(array_unique($tmp));
//输出
array (
0 => '139 9182 8973',
1 => '144 7038 6282',
2 => '182 2183 9323',
3 => '176 1226 2322',
4 => '183 1072 4890',
5 => '153 8744 2917',
6 => '152 1150 5508',
7 => '147 3404 5840',
8 => '139 3547 8652',
9 => '151 1968 2090',
)</code></pre>
<h3><a href="https://segmentfault.com/q/1010000007235729">global</a></h3>
<pre><code class="js">$var1 = 1;
function test(){
global $var1;//global $var1;等于$var1=&$GLOBALS['var1'];
unset($var1);
}
test();
echo $var1;// 此处输出1
$var1 = 1;
function test(){
unset($GLOBALS['var1']);
}
test();
echo $var1;// 此处报错PHP Notice: Undefined variable: var1</code></pre>
<h3>sprintf截取小数</h3>
<pre><code class="js">$str1 = 12.34;
$str2 = 12.35;
$str3 = 12.36;
echo sprintf('%.1f',$str1);//12.3
echo sprintf('%.1f',$str2);//12.3
echo sprintf('%.1f',$str3);//12.4
echo sprintf('%.1f', floor($str3));//12.3
echo sprintf('%.0f', 12.5); //12
echo sprintf('%.0f', 15.5); //16</code></pre>
<h3><a href="https://segmentfault.com/q/1010000007205669">php递归无限分类</a></h3>
<pre><code class="php">$pdo = new PDO("mysql:host=localhost;dbname=test", "root", "root");
function getCategories(PDO $pdo, $pid = 0)
{
$sql = 'SELECT * FROM `category` WHERE pid=:pid';
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':pid', $pid, PDO::PARAM_INT);
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($data as &$row) {
$row['subs'] = getCategories($pdo, $row['id']);
}
return $data;
}
$a = getCategories($pdo);
print_r($a);</code></pre>
<h3>递归</h3>
<pre><code>public function find_children_cat($cat_id, $data)
{
static $tem=array();
foreach ($data as $val)
{
if ( $val['parent_id'] == $cat_id )
{
array_push($tem, $val['cat_id']);
$this->find_children_cat($val['cat_id'], $data);
}
}
return $tem;
}</code></pre>
<h3>HTTP Basic Authorization</h3>
<pre><code class="js"> //请求的时候添加 Authorization头,值为"Basic "+base64_encode(username+':'+password)
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, "[$username]:[$password]");</code></pre>
<h3>switch全等判断</h3>
<pre><code class="js"> switch($value){
case null: echo 'null';
break;
case '': echo '空';
break;
}
当$value = ''时,switch会进入第一个case
switch(true) {
case null === $value : echo 'null';
break;
case '' === $value: echo '空';
break;
}
/**
* 移除字符串的BOM
*
* @param string $str 输入字符串
* @return string 输出字符串
*/
function removeBOM($str)
{
$str_2 = substr($str, 0, 2);
$str_3 = substr($str, 0, 3);//$str_2.$str{2};
$str_4 = substr($str, 0, 4);//$str_3.$str{3};
if ($str_3 == pack('CCC',0xef,0xbb,0xbf)) //utf-8
return substr($str, 3);
elseif ($str_2 == pack('CC',0xfe,0xff) || $str_2 == pack('CC',0xff,0xfe)) //unicode
return substr($str, 2);
elseif ($str_4 == pack('CCCC',0x00,0x00,0xfe,0xff) || $str_4 == pack('CCCC',0xff,0xfe,0x00,0x00)) //utf-32
return substr($str, 4);
return $str;
}</code></pre>
<h3><a href="https://segmentfault.com/q/1010000007263286">数组重新组合</a></h3>
<pre><code class="js"> $arr1 = [
['tracking1','abc@qq.com','80'],
['tracking1','abc@qq.com','50'],
['tracking2','efg@qq.com','60'],
['tracking2','efg@qq.com','30'],
];
$arr2 = [];
foreach ($arr1 as $data) {
list($account,$mail,$val) = $data;
isset($arr2[$account.$mail]) || $arr2[$account.$mail]=[$account,$mail,[]];
array_push($arr2[$account.$mail][2],$val);
}
$arr2 = array_values($arr2);
var_dump($arr2);
$arr = [['tracking1','abc@qq.com','80'],
['tracking1','abc@qq.com','50'],
['tracking2','efg@qq.com','60'],
['tracking2','efg@qq.com','30']];
$finalArr = [[[]]];
$mailArr =[];
foreach ($arr as $k=>$v){
$mailKey = array_search($v[1],$mailArr);
if($mailKey!==false){
array_push($finalArr[$mailKey][2],$v[2]);
}else{
$finalArr[$k] = $v;
$finalArr[$k][2] = [$v[2]];
$mailArr[$k]=$v[1];
}
}
$finalArr = array_values($finalArr);
var_dump($finalArr);</code></pre>
<h3>preg_replace_callback</h3>
<pre><code class="js">$items = [
'a > 1',
'b > 0',
'abc' => 'c > 1'
];
$subject = '#0 and #1 or (#0) and #abc #nooo';
echo preg_replace_callback('/#([a-z0-9_]+)/i', function($v) use ($items){
return isset($items[$v[1]]) ? $items[$v[1]] : $v[0];
}, $subject);//a > 1 and b > 0 or (a > 1) and c > 1 #nooo</code></pre>
<h3><a href="https://segmentfault.com/q/1010000007346139">用json保存二进制数</a></h3>
<p><code>$data = ['a1' => sprintf('0b%06b', 0b000100)]; // 转成JSON后: {"a1": "0b000100"}</code></p>
<h3>保留1位小数,不四舍五入,为整数时补0</h3>
<p>echo sprintf('%.1f', floor($str));<br>sprintf('%.1f',12.35);//12.3<br>sprintf('%.1f',12.36);//12.4<br>number_format(12.35,1,'.','')//12.4<br>number_format(12.36,1,'.','')//12.4</p>
<h3><a href="https://link.segmentfault.com/?enc=95weGcyt%2Fc3VISECCmRzPg%3D%3D.cNEdATbCDVy8VLEXG%2F7SdopCPNC74s4WAnY3tK664o%2FlLMwI72NTlxLmA1bzMksw" rel="nofollow">json_decode 后,数字对象转换成了 科学计数法</a></h3>
<pre><code class="php">$obj='{"order_id":213477815351175,"buyer":100001169269154}';
$obj=$this->json_decode($obj,TRUE);
print_r($obj);
Array
(
[order_id] => 2.1347781535118E+14
[buyer] => 1.0000116926915E+14
)
$obj='{"order_id":213477815351175,"buyer":100001169269154}';
$obj=$this->json_decode($obj,TRUE);
foreach ($obj as $key=>$val){
$obj[$key]=number_format($val,0,'','');
}
print_r($obj);
Array
(
[order_id] => 213477815351175
[buyer] => 100001169269154
)</code></pre>
<h3>从指定数字中获取随机组合的方法</h3>
<pre><code class="php">//http://blog.csdn.net/fdipzone/article/details/51794055
function getNumGroups($var, $num){
// 数量不正确
if($var<$num){
return array();
}
$total = 0;
$result = array();
for($i=1; $i<$num; $i++){
$tmp = mt_rand(1, $var-($num-$i)-$total);
$total += $tmp;
$result[] = $tmp;
}
$result[] = $var-$total;
return $result;
}
$result = getNumGroups(100, 3);
print_r($result);
Array
(
[0] => 42
[1] => 25
[2] => 33
)</code></pre>
<h3>crontab 精确到执行分钟内某一秒执行的方法</h3>
<pre><code class="js">test.php
echo date('Y-m-d H:i:s').PHP_EOL;
* * * * * php /Users/fdipzone/test.php >> /Users/fdipzone/test.log
* * * * * sleep 30; php /Users/fdipzone/test.php >> /Users/fdipzone/test.log</code></pre>
<h3>callable强制指定回调类型</h3>
<pre><code class="js">function dosth($callback){
call_user_func($callback);
}
function callback(){
echo 'do sth callback';
}
dosth('callback');
function dosth(callable $callback){
call_user_func($callback);
}
dosth('abc');//提示错误:TypeError: Argument 1 passed to dosth() must be callable </code></pre>
<h3>lcg_value与mt_rand生成0~1随机小数的效果比较</h3>
<pre><code class="js">/**
* 生成0~1随机小数http://blog.csdn.net/fdipzone/article/details/52829930
* @param Int $min
* @param Int $max
* @return Float
*/
function randFloat($min=0, $max=1){
return $min + mt_rand()/mt_getrandmax() * ($max-$min);
}
// 获取microtime
function get_microtime(){
list($usec, $sec) = explode(' ', microtime());
return (float)$usec + (float)$sec;
}
lcg_value();
//lcg_value()执行速度快,但随机效果不及基于mt_rand()与mt_getrandmax()算法实现
header('content-type: image/png');
$im = imagecreatetruecolor(512, 512);
$color1 = imagecolorallocate($im, 255, 255, 255);
$color2 = imagecolorallocate($im, 0, 0, 0);
for($y=0; $y<512; $y++){
for($x=0; $x<512; $x++){
$rand = randFloat();
if(round($rand,2)>=0.5){
imagesetpixel($im, $x, $y, $color1);
}else{
imagesetpixel($im, $x, $y, $color2);
}
}
}
imagepng($im);
imagedestroy($im);
/**
* 检查连接是否可用
* @param Link $dbconn 数据库连接
* @return Boolean
*/
function pdo_ping($dbconn){
try{
$dbconn->getAttribute(PDO::ATTR_SERVER_INFO);
} catch (PDOException $e) {
if(strpos($e->getMessage(), 'MySQL server has gone away')!==false){
return false;
}
}
return true;
}</code></pre>
<h3><a href="https://segmentfault.com/q/1010000007443484">Maximum function nesting level of '100' reached, aborting! in</a></h3>
<pre><code class="js">function test() {
echo count(debug_backtrace()) . "\n";
}
function test2() {
test();
}
test(); //输出1
test2(); //输出2
惰加载 只是给$this->['config']一个匿名函数,当你要用到的时候,才会进行new Config($config)的操作
public function __construct($config)
{
parent::__construct();
$this['config'] = function () use ($config) {
return new Config($config);
};</code></pre>
<h3>laravel验证两个字段必须有一个必填</h3>
<pre><code class="js">'email' => 'required_without:phone',
'phone' => 'required_without:email',
set_time_limit 可以控制秒级的最大执行时间,一个500毫秒的超时
declare(ticks=1);
$start = microtime(true);
register_tick_function(function () use ($start) {
(microtime(true) - $start < 0.5) or die("timeout\n");
});
function a() {
echo "do some work\n";
usleep(600000);
echo "do another work\n";
}
a();</code></pre>
<h3><a href="https://segmentfault.com/a/1190000006220620#articleHeader9">利用cookie模拟登陆</a></h3>
<pre><code class="php">//设置post的数据
$post = array (
'email' => '账户',
'pwd' => '密码'
);
//登录地址
$url = "登陆地址";
//设置cookie保存路径
$cookie = dirname(__FILE__) . '/cookie.txt';
//登录后要获取信息的地址
$url2 = "登陆后要获取信息的地址";
//模拟登录
login_post($url, $cookie, $post);
//获取登录页的信息
$content = get_content($url2, $cookie);
//删除cookie文件
@ unlink($cookie);
var_dump($content);
//模拟登录
function login_post($url, $cookie, $post) {
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 0);
curl_setopt($curl, CURLOPT_COOKIEJAR, $cookie);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($post));
curl_exec($curl);
curl_close($curl);
}
//登录成功后获取数据
function get_content($url, $cookie) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie);
$rs = curl_exec($ch);
curl_close($ch);
return $rs;
} </code></pre>
<h3>php self</h3>
<pre><code class="js">class Base {
public function log() {
// 目标类,输出:A/C
echo static::class;
// 基类,输出:Base
//echo __CLASS__;
echo self::class;
}
}
class A extends Base {
public function log1() {
echo self::class;
}
}
class C extends A {
public function log2() {
echo self::class;
}
}
//self 指向基类 Fruit,也就是 __CLASS__ 的类
//static、$this 指向最终new的类 Apple
$a = new A();$c = new C();
$a->log(); //输出 A Base
$c->log(); //输出 C Base
$c->log1(); //输出 A
$c->log2(); //输出 C</code></pre>
<h3><a href="https://segmentfault.com/q/1010000007074744">mysql session cookie </a></h3>
<pre><code class="php">CREATE TABLE sessions (
user_id int(10) unsigned NOT NULL,
session text NOT NULL,
md5 char(32) NOT NULL,
PRIMARY KEY (user_id)
) ENGINE=MEMORY DEFAULT CHARSET=utf8;
其中:
user_id存储的是用户ID,作为主键.
session存储的是用户的会话数组经过serialize或json_encode后的字符串.
md5存储的是session字段的MD5值,用于实现Check And Set版本号乐观锁:
--读取会话
SELECT session, md5 --写入会话时需要用到这里查出来的md5,就是下面的$last_md5
FROM sessions WHERE user_id = $user_id
--写入会话
UPDATE sessions
SET session = $str, md5 = md5($str)
WHERE user_id = $user_id
AND md5 = $last_md5 --检查MD5,确保session字段没有被修改过</code></pre>
python操作selenium的基本操作
https://segmentfault.com/a/1190000006998942
2016-09-24T23:18:30+08:00
2016-09-24T23:18:30+08:00
苏生不惑
https://segmentfault.com/u/sushengbuhuo
0
<pre><code class="php">#coding:utf-8
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains #引入ActionChains鼠标操作类
from selenium.webdriver.common.keys import Keys #引入keys类操作
import time
def s(int):
time.sleep(int)
browser = webdriver.Chrome()
browser.get('http://www.baidu.com')
print '现在将浏览器最大化'
browser.maximize_window()
text = browser.find_element_by_name('tj_duty').text
print text #打印备案信息
browser.find_element_by_id('kw1').send_keys(u'杨彦星')
print browser.find_element_by_id('kw1').get_attribute('type')
print browser.find_element_by_id('kw1').size #打印输入框的大小
browser.find_element_by_id('su1').click()
time.sleep(3)
print '现在我将设置浏览器为宽480,高800显示'
browser.set_window_size(480,800)
browser.get('http://m.mail.10086.cn')
time.sleep(3)
print '现在我将回到刚才的页面'
browser.maximize_window()
browser.back()
time.sleep(3)
print '现在我将回到之前的页面'
browser.forward()
time.sleep(5)
print '现在我将打开杨彦星的网站进行json搜索'
browser.get('http://static.yangyanxing.com')
browser.find_element_by_xpath(".//*[@id='ls']").send_keys(u'json')
browser.find_element_by_xpath(".//*[@id='header']/div[1]/div/form/input[2]").click()
time.sleep(5)
browser.quit()
browser = webdriver.Chrome()
print '以下将以登录人人网来进行上面的综合应用'
browser.get('http://www.renren.com/SysHome.do')
browser.find_element_by_id('email').clear()#这个是以id选择元素
browser.find_element_by_id('email').send_keys('email')
browser.find_element_by_id('email').send_keys(Keys.BACK_SPACE)
time.sleep(2)
browser.find_element_by_id('email').send_keys('m')
s(2)
browser.find_element_by_id('email').send_keys(Keys.CONTROL,'a')
s(2)
browser.find_element_by_id('email').send_keys(Keys.CONTROL,'x')#剪切掉里面的内容
s(2)
browser.find_element_by_id('email').send_keys(Keys.CONTROL,'v') #重新输入进去
s(2)
browser.find_element_by_name('password').clear()#这个是以name选择元素
browser.find_element_by_name('password').send_keys('password')
#browser.find_element_by_xpath(".//*[@id='login']").click()#这个是以xpath选择元素
browser.find_element_by_xpath(".//*[@id='login']").send_keys(Keys.ENTER) #这里通过点击Enter键来登录
browser.maximize_window()
article = browser.find_element_by_link_text(u'周碧华:社科院出现内鬼意味着什么?')
ActionChains(browser).move_to_element(article).perform()#将鼠标移动到这里,但是这里不好用
ActionChains(browser).context_click(article).perform()
time.sleep(5)
browser.quit()
# 店铺签到https://www.v2ex.com/t/321539
def shop_check_in(self):
urls = [
'https://nongfutechan.taobao.com/ugo.htm?spm=a217e.7759359.15285.1.4xE9Il&signin=true#ugo-jinbi',
'https://shop136560499.taobao.com/ugo.htm?spm=a217e.7759359.15285.2.muhVBy&signin=true#ugo-jinbi',
'https://shop33473134.taobao.com/ugo.htm?spm=a217e.7759359.15285.3.yW2N4E&signin=true#ugo-jinbi'
]
for url in urls:
self.driver.get(url)
time.sleep(5)
print("page_source\t%s" % self.driver.page_source)
self.driver.find_element_by_xpath('//a[@href="#" and @class="now-take J_NowSignIn" and text()="立即签到"]').click()
增加 wait 时间,确保新页面已经完全加载
用 Google Chrome 的 XPath Helper 插件,确保自己写的 XPath selector 无误
打印源代码 driver.page_source ,确认页面内有「立即签到」这个元素,并且 XPath selector 无误</code></pre>
<p>from <a href="https://link.segmentfault.com/?enc=5nOn1XA9ItDfIpwpdm683Q%3D%3D.HJ4cxYEuQlgN%2FUJFvead0FoyPAlNctkXIxLrsP%2BycllkllY6RYChtbUb9ZwNFEfx" rel="nofollow">http://www.yangyanxing.com/ar...</a></p>
javascript记录
https://segmentfault.com/a/1190000006877590
2016-09-11T18:20:42+08:00
2016-09-11T18:20:42+08:00
苏生不惑
https://segmentfault.com/u/sushengbuhuo
1
<h3>记录错误日志</h3>
<pre><code class="php">window.onerror = function(message, url, lineNumber,columnNo,error) {
var data = {
'message':message,
'url':url,
'error':error.stack
};
$.ajax({
url:"/error/capture",
type:'post',
data:data,
success:function(){
}
});
return true;
};</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=cOehAALotuO8rqN%2FgVMtvA%3D%3D.I0Mi49yCKL0xr3dDeFyfsEiutScwp9pNf4rt2MrX7sQOKcJmgnT5Z87eCx6%2B%2BUNKrINYYB6CayWb6OhpWXy1yQ%3D%3D" rel="nofollow">javascript随机数生成算法</a></h3>
<pre><code class="php">function rnd( seed ){
seed = ( seed * 9301 + 49297 ) % 233280; //为何使用这三个数?
return seed / ( 233280.0 );
};
function rand(number){
today = new Date();
seed = today.getTime();
return Math.ceil( rnd( seed ) * number );
};
myNum=(rand(5));
var rand = (function(){
var seed = (new Date()).getTime()
function r(){
seed = (seed*9301+49297)%233280
return seed/(233280.0)
}
return function(number){
return Math.ceil(r()*number)
}
})()
rand = (function(){
var today = new Date();
var seed = today.getTime();
function rnd(){
seed = ( seed * 9301 + 49297 ) % 233280;
return seed / ( 233280.0 );
};
return function rand(number){
// return Math.ceil(rnd(seed) * number);
return Math.ceil(rnd() * number);
};
})();
myNum = (rand(5));
</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=viTQGof8JrsWKxh%2B5Su4Ww%3D%3D.x%2BwpLO7BXnkfo3NACUtLc7qWpdR6TxIMVjoJoSaLhMJZXQVjqeSPn%2BAyoGhtFzCICu%2FyY1eQ2MrlxxTnyTG4KA%3D%3D" rel="nofollow">JavaScript 中,如何求出两个数组的交集和差集</a></h3>
<pre><code class="php">_.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]);
=> [1, 2]
_.difference([1, 2, 3, 4, 5], [5, 2, 10]);
=> [1, 3, 4]
let a = new Set([1, 2, 3]);
let b = new Set([3, 5, 2]);
// 并集
let unionSet = new Set([...a, ...b]);
//[1,2,3,5]
// 交集
let intersectionSet = new Set([...a].filter(x => b.has(x)));
// [2,3]
// ab差集
let differenceABSet = new Set([...a].filter(x => !b.has(x)));
// [1]
再把Set转换为数组即可.
let arr = Array.from(set);
// 或 let arr = [...set];
相同的
a.filter(function(v){ return b.indexOf(v) > -1 })
不同的
a.filter(function(v){ return !(b.indexOf(v) > -1) }).concat(b.filter(function(v){ return !(a.indexOf(v) > -1)}))
</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=CUw7ww%2BLuiBoPmC45WBohA%3D%3D.LkzTNp6ZfzEzji23x2KOReR9hjmpd1HpY2%2FZsUcn0JimnHjQgscP1DTxqGbTDF5W" rel="nofollow">获取某个DOM元素绑定的事件</a></h3>
<pre><code class="php">getEventListeners($('selector')) 方法以数组对象的格式返回某个元素绑定的所有事件
getEventListeners($('#firstName')).click[0].listener 会返回ID为 firstName 元素绑定的click事件
inspect($('selector')) 会检查所有匹配选择器的DOM元素,并返回所有选择器选择的DOM对象。例如inspect($('#firstName')) 选择所有ID是 firstName 的元素,inspect($('a')[3]) 检查并返回页面上第四个 p元素。
$0, $1, $2等等会返回你最近检查过的几个元素,例如 $0 会返回你最后检查的元素,$1 则返回倒数第二个
</code></pre>
<p><img src="/img/bVDMks?w=600&h=165" alt="clipboard.png" title="clipboard.png"></p>
<p><img src="/img/bVDMkw?w=587&h=621" alt="clipboard.png" title="clipboard.png"></p>
<h3><a href="https://link.segmentfault.com/?enc=UC%2F5qLENgfXJHb6t7sO64A%3D%3D.Kq53fBqFvEn4h%2BcWDQeGXx2XcMO%2Fwuymr2SjLakvSI0%3D" rel="nofollow">img onerror事件触发</a></h3>
<pre><code class="php">
$('img').each(function() {
if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
this.src = 'default.png';
}
});</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=5ioppIgm7989imJR5e21EQ%3D%3D.8Dbb0UPrKSaZobuo47LDqlx%2FBSOuMkY2AtW%2BehLAQJU%3D" rel="nofollow">禁止浏览器记住密码</a></h3>
<p>在input[type=’password’]的前面加上一个隐藏的密码框即可,且要求是:不能添加id和name属性<br><input type='password' style='display:none;' /></p>
<h3>通过 js 修改微信浏览器的title</h3>
<pre><code class="php">var $body = $('body');
document.title = ‘title’
// hack在微信等webview中无法修改document.title的情况
var $iframe = $('<iframe src="/favicon.ico"></iframe>').on('load', function() {
setTimeout(function() {
$iframe.off('load').remove()
}, 0)
}).appendTo($body)</code></pre>
<h3>图片的预加载</h3>
<pre><code class="php">function imgLoad(src){
var img = new Image();
if(img.complete){ //从缓存里面取
callback();
}else{
img.onload = function(){ //实际加载完成
callback();
}
}
img.src = src;
}</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=hyxBZ8A9ndkU7DS0IZPQ8A%3D%3D.PHVs9GlpV4%2FkzXQUKkIst1WQ%2FWZoR%2FxBOmHl9QD8n4I%3D" rel="nofollow">实现类似于add(1)(2)(3)调用</a></h3>
<pre><code class="php">function add(x){
var sum = x;
var tmp = function(y){
sum = sum + y;
return tmp;
}
tmp.toString = function(){
return sum;
}
return tmp
}</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=UZzW4SiE14KJj3Eb%2FdlS9g%3D%3D.8%2FklnyWm1m4TNecgmbpaketflVWT2dIH7kWbdix%2FHGvMNd%2FOQ75GT5zoyIWPUC1K" rel="nofollow">用代码来画个国旗</a></h3>
<pre><code class="php"><html>
<head>
<script>
var col=new Array("red","brown");
var ticker=0;
var step=0;
function drawBackground(){
var g=document.getElementById("background").getContext("2d");
var grd=g.createLinearGradient(-560+ticker, 0, 1400+ticker,0);
for (var i=0; i<10; i++)
grd.addColorStop(i/10,col[(i + step)%col.length]);
ticker=ticker+10;
if (ticker>=196){
ticker=0;
step++;
}
g.fillStyle=grd;
g.fillRect(0,0,1600,700);
}
function preperation(){
setInterval('drawBackground()',100);
}
</script>
<style type="text/css">
#myCanvas{
z-index:2;
position:absolute; left:0px; top:-5px;
}
#background{
z-index:1;
position:absolute;
left:0px;
top:0px;
}
</style>
</head>
<body onLoad="preperation()">
<canvas id="myCanvas" width="900" height="600" >
Your browser does not support the HTML5 canvas tag.
</canvas>
<canvas id="background" width="1600" height="700" ></canvas>
<script>
var x=new Array(0,12,54,18,28,0,-28,-18,-54,-12,0); //五角星样品坐标xx数组
var y=new Array(-53,-17,-17,1,45,19,45,1,-17,-17,-53); //五角星样品坐标y数组
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d"); //获得画笔
//样品数组x轴坐标 a , 和y轴坐标 b
//指定位置[locationX,locationY]
//真实五角星的大小,与样品五角星尺寸之比 f
//五角星画完后,旋转的角度 rotation
function star(a,b,locationX,locationY,f,rotation){
ctx.save();//记录画图(画笔)的初始环境
ctx.translate(locationX,locationY);
ctx.rotate(rotation*Math.PI/180.0);
ctx.beginPath();
ctx.moveTo(Math.round(a[0]*f),Math.round(b[0]*f));
for (var i=1;i<a.length;i++)
ctx.lineTo(Math.round(a[i]*f),Math.round(b[i]*f));
ctx.closePath();
ctx.fillStyle="yellow";
ctx.fill();
ctx.restore();//还原画图(画笔)的初始环境
}
star(x,y,165,165,1.4,0);//画大五角星
star(x,y,301,65,0.5,30);//画小五角星
star(x,y,362,126,0.5,-30);//画小五角星
star(x,y,359,216,0.5,0);//画小五角星
star(x,y,301,273,0.5,30);//画小五角星
</script>
</body>
</html></code></pre>
<h3><a href="https://link.segmentfault.com/?enc=O7BS0EqHocGczJQFEkC11w%3D%3D.DaBT%2FVGRY%2FaiWqQrDeDDrOx6eJeuN%2FaXTIjRFcCPn7vsF1sZGnSS45rN5TG5ICRdCzSzE1vGKYqBvVuiQyCmawluXLOHJlbqJlfGNbjV280%3D" rel="nofollow">js获取URL中的参数</a></h3>
<pre><code class="php">function getQueryString(url, name) {
var reg = new RegExp("(^|&|\\?)" + name + "=([^&]*)(&|$)", "i");
var r = url.substr(1).match(reg);
if (r != null) return unescape(r[2]); return null;
} </code></pre>
<h3><a href="https://link.segmentfault.com/?enc=Yr7vgrdaCDX2hV%2FtU6BZYA%3D%3D.3szKbdzPZahuo73mgBJcioP1MykD3F3VZkkcTyjv5wd1sDLjz8dge6if8voKQF%2BYtzyRybnmYHBz6JkijQVmRQ%3D%3D" rel="nofollow">视频video标签在移动端的播放总结</a></h3>
<pre><code class="php">function video_loading( $video ){
$('.video_loading').show();
var timer = setInterval(function(){
var currentTime = $video[0].currentTime; // 检测当前的播放时间
if( currentTime>0 ){
$('.video_loading').hide();
clearInterval( timer );
}
}, 100)
}
/**
视频的播放时间改变时进行的操作
videoid video标签的id
cur 当前播放时间,可以传入ended参数
func 回调函数
*/
videoUpdate : function(videoid, cur, func){
var myVideo = document.getElementById(videoid);
if( myVideo ){
if( typeof cur =='number' ){
myVideo.addEventListener('timeupdate', function(){
if( this.currentTime>=cur ){
func();
myVideo.removeEventListener('timeupdate', function(){
}, false);
}
}, false);
}else{
myVideo.addEventListener(cur, function(){
func();
}, false);
}
}
}
// 第一屏的视频进行到4秒时,显示透明图层以提供用户操作
tool.videoUpdate( 'video1', 4, function(){
$('.s1 .overlay').show();
});
// 第一屏的视频结束时,显示向下滑动提示按钮
tool.videoUpdate( 'video1', 'ended', function(){
$('.s1 .tip').show();
});</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=D8BysWWP8eCr4sZ0c7I1Gg%3D%3D.APfhJg%2Bm0M1MTtGEWQ0vSNbWQcQ2EPgFqS%2BnC9luu2AU0Ktp%2BlRjTKQ475DvNENYXng3PHPojqZeqg89MuAG2w%3D%3D" rel="nofollow">为博客的文章添加二维码</a></h3>
<pre><code class="php">
$('.bcontent').append('<div class="qrcode"><a href="javascript:;">点击生成二维码,可在手机端观看</a><div class="tsp"></div></div>');
$('.bcontent').on('click', '.qrcode a', function(){
var $tsp = $(this).next();
if( $tsp.find('canvas').length ){
if( $tsp.css('display')=='block' ){
$tsp.hide();
}else{
$tsp.show();
}
}else{
if( self.showing ){
return;
}
self.showing = true;
$tsp.show().html( '正在生成中...' );
$.ajax({
url : 'jquery.qrcode.min.js',
dataType : 'script',
type : 'get'
}).done(function(){
self.showing = false;
$tsp.html('');
$tsp.qrcode({
render : 'canvas',
width : 176,
height: 176,
text : window.location.href
});
})
}
})
</code></pre>
<h3>使用DOM中的a标签解析url</h3>
<pre><code class="php">// 创建一个额外的a标签
function parseURL(url) {
var a = document.createElement('a');
a.href = url;
return {
source: url,
protocol: a.protocol.replace(':',''),
host: a.hostname,
port: a.port,
query: a.search,
params: (function(){
var ret = {},
seg = a.search.replace(/^\?/,'').split('&'),
len = seg.length, i = 0, s;
for (;i<len;i++) {
if (!seg[i]) { continue; }
s = seg[i].split('=');
ret[s[0]] = s[1];
}
return ret;
})(),
file: (a.pathname.match(/\/([^\/?#]+)$/i) || [,''])[1],
hash: a.hash.replace('#',''),
path: a.pathname.replace(/^([^\/])/,'/$1'),
relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [,''])[1],
segments: a.pathname.replace(/^\//,'').split('/')
};
}
var myURL = parseURL('http://abc.com:8080/dir/index.html?id=255&m=hello#top');
myURL.file; // 'index.html'
myURL.hash; // 'top'
myURL.host; // 'abc.com'
myURL.query; // '?id=255&m=hello'
myURL.params; // Object = { id: 255, m: hello }
myURL.path; // '/dir/index.html'
myURL.segments; // Array = ['dir', 'index.html']
myURL.port; // '8080'
myURL.protocol; // 'http'
myURL.source; // 'http://abc.com:8080/dir/index.html?id=255&m=hello#top'</code></pre>
<h3>javascript如何添加前置0</h3>
<pre><code class="php">function addPreZero(num){
return ('000000000'+num).slice(-10);
}</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=YQXS6pdDapdtE%2B5eQolR2w%3D%3D.hgegts3FNps9ky%2F0Q215heX61Z7LDnMLdzJ%2FiOXXSJJ5ZJCs1D2InL7LmOdriC47DT0ZolerPq8QI9wXAm0dsF96UICcmcUl4mrkJzxGprk%3D" rel="nofollow">html5实现图片预览和查看原图</a></h3>
<pre><code class="php"><input type="file" id='upimg' />
var upimg = document.querySelector('#upimg');
upimg.addEventListener('change', function(e){
var files = this.files;
if(files.length){
// 对文件进行处理,下面会讲解checkFile()会做什么
checkFile(this.files);
}
});
// 图片处理
function checkFile(files){
var file = files[0];
var reader = new FileReader();
// show表示<div id='show'></div>,用来展示图片预览的
if(!/image\/\w+/.test(file.type)){
show.innerHTML = "请确保文件为图像类型";
return false;
}
// onload是异步操作
reader.onload = function(e){
show.innerHTML = '<img src="'+e.target.result+'" alt="img">';
}
reader.readAsDataURL(file);
}</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=wea6V6c8pBVFpvJo0Yqr6w%3D%3D.MOlQXgCPsnz6VKcoA%2F6RgOq7CwFI3P5Tn2TYGHOZsNIEbna%2B7lrcZRk5n6dCNbDbO9N8lzky9kcYgeqt6d6iSQ%3D%3D" rel="nofollow">移动端在页面输出调试信息</a></h3>
<pre><code class="php">function log(){
try{
throw new Error();
}catch(e){
console.log(e.stack);
}
}
log();
function log(msg){
var $body = document.querySelector('body');
if( !$body.querySelector('.info_wz_852') ){
$body.innerHTML += '<div class="info_wz_852" style="position:fixed;top:0;left:0;z-index:99999; background:#000;color:#f00;"></div>';
}
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 += '<p>['+minute+':'+second+'] '+loc+'</p><p>'+msg+'</p><br/>';
}
}</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=FLrbC%2BAuf21axw4xF1YaDg%3D%3D.DQfhJvoPCVmhisjR0Oui5ttXeCrIK0kSSkIQtRKTYv8%3D" rel="nofollow">判断 x 是否是整数</a></h3>
<pre><code class="php">function isInteger(x) {
return parseInt(x, 10) === x;
}
function add(x, y) {
return x.toPrecision() + y.toPrecision()
}
console.log(add(0.1,0.2));
function add(num1, num2){
let r1, r2, m;
r1 = (''+num1).split('.')[1].length;
r2 = (''+num2).split('.')[1].length;
m = Math.pow(10,Math.max(r1,r2));
return (num1 * m + num2 * m) / m;
}
console.log(add(0.1,0.2)); //0.3
console.log(add(0.15,0.2256)); //0.3756</code></pre>
<h3>PhantomJS抓取网页并将它渲染成图片</h3>
<pre><code class="php">var page = require('webpage').create();
page.settings.userAgent = 'WebKit/534.46 Mobile/9A405 Safari/7534.48.3';
page.settings.viewportSize = { width: 400, height: 600 };
page.open('http://m.bbc.co.uk/news/business', function (status) {
if (status !== 'success') {
console.log('Unable to load BBC!');
phantom.exit();
} else {
window.setTimeout(function () {
page.clipRect = { left: 0, top: 0, width: 400, height: 600 };
page.render('bbc-page1.png');
page.clipRect = { left: 0, top: 600, width: 400, height: 600 };
page.render('bbc-page2.png');
phantom.exit();
}, 2000);
}
});</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=kb6m8%2FhN5bj5jSr59rcumA%3D%3D.b036uN5eoQapiMFZiDXadvOpI628nExsp5C91GeUeY66vMTXbqn8sHLLBDe0Jq1b3DKuqHdDS1bRe2I1HW6dTq6zDlBYBtMyHv7%2FjJNHCjVSwx89gQLZ06aRe3WaSq5Ugd5pIdKf2Oq5u%2BxuEdJUnw%3D%3D" rel="nofollow">复制与粘贴</a></h3>
<pre><code class="php">
<p>Email me at <a class="js-emaillink" href="mailto:matt@example.co.uk">matt@example.co.uk</a></p>
<p><button class="js-emailcopybtn"><img src="./images/copy-icon.png" /></button></p>
var copyEmailBtn = document.querySelector('.js-emailcopybtn');
copyEmailBtn.addEventListener('click', function(event) {
// Select the email link anchor text
var emailLink = document.querySelector('.js-emaillink');
var range = document.createRange();
range.selectNode(emailLink);
window.getSelection().addRange(range);
try {
// Now that we've selected the anchor text, execute the copy command
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Copy email command was ' + msg);
} catch(err) {
console.log('Oops, unable to copy');
}
// Remove the selections - NOTE: Should use
// removeRange(range) when it is supported
window.getSelection().removeAllRanges();
});</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=3h%2BVIAqAaKAmdJQpRr2Y8w%3D%3D.2lg3XLOOttQUaQlK8P6uligniN%2B4TOAxv%2FoXtmcNET0HpetmDj%2B8JLT9QOXUhjfG" rel="nofollow">倒计时的JS</a></h3>
<pre><code class="php">
var time_distance;
var totleTime;
var stop;
function countdownTime(disTime){
time_distance =disTime;
totleTime=time_distance;
showTime();
}
function showTime(){
time_distance=totleTime;
var day=0,
hour=0,
minute=0,
second=0;//时间默认值
if(time_distance > 0){
day = Math.floor(time_distance / (60 * 60 * 24*1000));
hour = Math.floor(time_distance / (60 * 60*1000)) - (day * 24);
minute = Math.floor(time_distance / (60*1000)) - (day * 24 * 60) - (hour * 60);
second = Math.floor(time_distance/1000) - (day * 24 * 60 * 60) - (hour * 60 * 60) - (minute * 60);
}
if (hour <= 9) hour = '0' + hour;
if (minute <= 9) minute = '0' + minute;
if (second <= 9) second = '0' + second;
// 显示时间
$("#time_d").text(day+'天');
$("#time_h").text(hour+'时');
$("#time_m").text(minute+'分');
$("#time_s").text(second+'秒');
stop=setTimeout("showTime()",1000);
totleTime=totleTime-1000;
if(totleTime<1000){
$("#time_d").text('活动');
$("#time_h").text('已经');
$("#time_m").text('结束');
$("#time_s").text('。');
clearTimeout(stop);
}
}</code></pre>
<h3>一个数每隔一秒执行加1并打印出来</h3>
<pre><code class="php">var count = (function() {
var timer;
var i = 0;
function change(tar) {
i++;
console.log(i);
if (i === tar) {
clearTimeout(timer);
return false;
}
timer = setTimeout(function() {
change(tar)
}, 1000)
}
return change;
})()
count(50)</code></pre>
<h3>onerror log</h3>
<pre><code class="php">'use strict';
function errorHandler( message, source, lineno, colno, error){
var errorDiv = document.getElementById("error");
errorDiv.classList.remove("hide");
console.log("Error happened, message:", message);
console.log("On source file: ", source);
console.log("On line - col: ", lineno, "-", colno);
console.log("Error:", error);
try {
var ua = navigator.userAgent;
console.log("UA: ", ua);
} catch (e) {
console.log("Unable to get UA");
}
}
window.onerror = errorHandler;</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=FtOUZOT670DMi%2F7v12BlIQ%3D%3D.v%2FaQQUK6XWnz%2FuDsdUeKw3ROS74adrjQMBrw4ZUWgBe6gPPd9Zwr95ByuBGePEZkDVAUzXmEp7h7Mu%2F6aHKocqMUVRw57QS1e2eiiBXH%2BpxpG%2FqY90lSGYaY5tAjVApY" rel="nofollow">javascript copy</a></h3>
<pre><code class="php"><div class="line copyAsText">
<label for="bbcode" class="copyBtn">BBCode</label>
<input name="bbcode" value="[img]http://7sdream-rikka-demo.daoapp.io/files/95356e2f-7648-431f-8fe3-754d833d6cc1.png[/img]" disabled/>
</div>
'use strict';
function addCopyEventListener(url){
var divs = document.querySelectorAll("div.copyAsText");
for (var index in divs) {
if(!divs.hasOwnProperty(index)) {
continue;
}
var div = divs[index];
var input = div.querySelector("input");
var btn = div.querySelector("label");
if (url !== "") {
var template = input.getAttribute("data-template");
input.value = template.replace("${url}", url);
}
void function(btn, input){
btn.addEventListener("click", function(){
if (btn.disabled) {
return;
}
var res = false;
try {
input.disabled = false;
var section = window.getSelection();
section.removeAllRanges();
input.focus();
input.setSelectionRange(0, input.value.length);
res = document.execCommand("copy");
input.disabled = true
} catch(e) {
res = false;
}
if (res) {
var origin = btn.textContent;
btn.textContent = "Copied!";
btn.disabled = true;
setTimeout(function(){
btn.textContent = origin;
btn.disabled = false;
}, 2000);
} else {
window.prompt("Copy to clipboard: Ctrl+C, Enter", input.value);
}
});
}(btn, input);
}
}
addCopyEventListener("");
//https://github.com/imsobear/blog/issues/31
//只需要对相应的元素绑定 mouseenter 的事件,然后响应 selectText() 这个方法就 ok
function selectText (element) {
var text = element,
range,
selection;
if (body.createTextRange) {
// IE
range = body.createTextRange();
range.moveToElementText(text);
range.select();
} else if (window.getSelection) {
// Others
selection = window.getSelection();
range = doc.createRange();
range.selectNodeContents(text);
selection.removeAllRanges();
selection.addRange(range);
} else {
return false;
}
}</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=Hr9YCbf3ViHeYgpDjSQ%2BCA%3D%3D.EbBSyT%2BzBHO8t0A4gXmdLh2aUKBSsI5TzUa3%2BXX%2Bid76PHWDcLBgQ8%2FaqitEJWZx5fJX1dcSw8NLe%2FbIh6lOYQ%3D%3D" rel="nofollow">把节点列表(NodeList)转换为数组</a></h3>
<pre><code class="php">var elements = document.querySelectorAll("p"); // NodeList
var arrayElements = [].slice.call(elements); // 现在 NodeList 是一个数组
var arrayElements = Array.from(elements); // 这是另一种转换 NodeList 到 Array 的方法
var array1 = [1,2,3];
var array2 = [4,5,6];
console.log(array1.push.apply(array1, array2)); // [1,2,3,4,5,6];</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=PtLwTe0T65xxDmZKdzJahQ%3D%3D.Gft6%2B3lNWm1lquG%2B2LqUB0b32rnIqB0%2B8%2F7X9Lymqm%2FkK%2B%2FP%2FOCXV7PumWkItp29" rel="nofollow">JavaScript实现字符串长度截取</a></h3>
<pre><code class="php">
function cutstr(str, len) {
var temp;
var icount = 0;
var patrn = /[^\x00-\xff]/;
var strre = "";
for (var i = 0; i < str.length; i++) {
if (icount < len - 1) {
temp = str.substr(i, 1);
if (patrn.exec(temp) == null) {
icount = icount + 1
} else {
icount = icount + 2
}
strre += temp
} else {
break
}
}
return strre + "..."
}
function $(id) {
return !id ? null : document.getElementById(id);
}
// 用法:如果地址是 test.htm?t1=1&t2=2&t3=3, 那么能取得:GET["t1"], GET["t2"], GET["t3"]
function get_get(){
querystr = window.location.href.split("?")
if(querystr[1]){
GETs = querystr[1].split("&")
GET =new Array()
for(i=0;i<GETs.length;i++){
tmp_arr = GETs[i].split("=")
key=tmp_arr[0]
GET[key] = tmp_arr[1]
}
}
return querystr[1];
}
/**
* 判断变量是否空值
* undefined, null, '', false, 0, [], {} 均返回true,否则返回false
*/
function empty(v){
switch (typeof v){
case 'undefined' : return true;
case 'string' : if(trim(v).length == 0) return true; break;
case 'boolean' : if(!v) return true; break;
case 'number' : if(0 === v) return true; break;
case 'object' :
if(null === v) return true;
if(undefined !== v.length && v.length==0) return true;
for(var k in v){return false;} return true;
break;
}
return false;
}
function backTop(btnId) {
var btn = document.getElementById(btnId);
var d = document.documentElement;
var b = document.body;
window.onscroll = set;
btn.style.display = "none";
btn.onclick = function() {
btn.style.display = "none";
window.onscroll = null;
this.timer = setInterval(function() {
d.scrollTop -= Math.ceil((d.scrollTop + b.scrollTop) * 0.1);
b.scrollTop -= Math.ceil((d.scrollTop + b.scrollTop) * 0.1);
if ((d.scrollTop + b.scrollTop) == 0) clearInterval(btn.timer, window.onscroll = set);
},
10);
};
function set() {
btn.style.display = (d.scrollTop + b.scrollTop > 100) ? 'block': "none"
}
};
backTop('goTop');
</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=GOYLPoPGoTmTm%2BBjg8CBvg%3D%3D.E6ABy8CFeMaAVpS4DROkajZaXSp50KQqOTtxszxzkOcCpPm4B7or5VGfRyE13XrIs%2Brtnwim4WORVkCS6WmX5t6L%2FQO0DP4PvTjHGDPK3fviWV%2BnJYHLZuBybCeqv9W6skdrSdJ8CRT2Acq8b9qWWIa7MvkPIHQ8tA140YM49Sk%3D" rel="nofollow">mockjs让前端开发独立于后端</a></h3>
<pre><code class="php">
<script src="http://mockjs.com/dist/mock.js"></script>
<script>
//调用mock方法模拟数据
Mock.mock('http://laoyu', {
"errorcode": 0,//0表示成功,1表示错误
"message": "xx信息不完整", //弹出错误信息
});
//使用ajax进行测试
var xhr = XMLHttpRequest();
xhr.open("post","http://laoyu",true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send(null);
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
if((xhr.status>=200 && xhr.status<300) || xhr.status== 304){
var data = JSON.parse(xhr.responseText);
//因为reponseText返回的是字符串,将字符串转换成我们想要的JSON数据,这样就可以调用了
console.log(data); //在控制台中打印出返回的内容
}else{
alert("Request was unsuccessful: " + xhr.status);
}
}
}
</script>
</code></pre>
<h3>rand num</h3>
<pre><code class="php">
function GetRandomNum(Min,Max)
{
var Range = Max - Min;
var Rand = Math.random();
return(Min + Math.round(Rand * Range));
}
var num = GetRandomNum(10,100); </code></pre>
<h3>创建XMLHttpRequest对象</h3>
<pre><code class="php">function createXHR(){
if(typeof XMLHttpRequest != "undefined"){
return new XMLHttpRequest();
}else if(typeof ActiveXObject != "undefined"){
if(typeof arguments.callee.activeXString != "string"){
var versions = ["MSXML2.XMLHttp.6.0","MSXML2.XMLHttp. 3.0","MSXML2.XMLHttp"],i,len;
for(i = 0,len=versions.length;i<len;i++){
try{
new ActiveXObject(versions[i]);
arguments.callee.activeXString = versions[i];
break;
}catch(ex){
//跳过
}
}
}
return new ActiveXObject(arguments.callee.activeXString);
}else{
throw new Error("No XHR object available.");
}
}
var xhr = createXHR();
xhr.open("post","check.php",true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send(null);
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
if((xhr.status>=200 && xhr.status<300) || xhr.status== 304){
alert(xhr.responseText);
}else{
alert("Request was unsuccessful: " + xhr.status);
}
}
}</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=wVhhBi09LPbmOz5Bh2xNGg%3D%3D.klSnREM%2FLtcjvVSuHWajZ5rLkQc%2BZb0HvisS%2FrPEDRgJs3K%2BU%2FZ0XApZpfUke%2FNKPacMJr6jORyemP%2F5LyAlbUjkfX1QnYLRu9xB9hhchXk%2B3lqLh8jJ8t561j1jXtskg2BPzcIf1iLZ963dFlCPRZ5uP4r0duh%2FkhDQ19Lr%2B4jjP1pr9Pd6j4EvSqtu%2FkdP" rel="nofollow">多行文本溢出显示省略号</a></h3>
<p>var module = document.getElementById("clamp-this-module");<br>$clamp(module, {clamp: 3});</p>
<h3><a href="https://link.segmentfault.com/?enc=Pa8qj1Kr0b%2BGHFeuoup2FQ%3D%3D.jyKIUxoPuElXFJPpq2hvbv1p71v6kRmB%2Fs%2FcnGYZN0V53UAIl7ljYF4IobdWLM68e5YWhwKIi9cBm2CCT4eBVq%2Bbu7a5xZyAIhBfDsUrvK%2BfBTvRqivXU9hrMuzeNvgKUjbJVOF71qUYs7nhOFbBjsuZr9i0DM6pKiv9DgIe2IICPg5k8b6Ii40x0GvmtnMg%2BEvJ9NW1YNFVmBIToIGOajgDxji1Cb9HF%2Ba4%2F2vGzvJ2sQIhL5ifVnBN52poqS5r" rel="nofollow">微信页面监听摇一摇事件,并伴有音效</a></h3>
<pre><code class="php"><audio style="display: none;" src="http://xunlei.sc.chinaz.com/files/download/sound1/201410/5018.mp3" id="musicBox" preload="preload" controls></audio>
<script>
var SHAKE_THRESHOLD = 3000;
var last_update = 0;
var x=y=z=last_x=last_y=last_z=0;
var media;
media= document.getElementById("musicBox");
function init(){
last_update=new Date().getTime();
if (window.DeviceMotionEvent) {
window.addEventListener('devicemotion',deviceMotionHandler, false);
} else{
alert('not support mobile event');
}
}
function deviceMotionHandler(eventData) {
var acceleration =eventData.accelerationIncludingGravity;
var curTime = new Date().getTime();
if ((curTime - last_update)> 100) {
var diffTime = curTime -last_update;
last_update = curTime;
x = acceleration.x;
y = acceleration.y;
z = acceleration.z;
var speed = Math.abs(x +y + z - last_x - last_y - last_z) /
diffTime * 10000;
if (speed > SHAKE_THRESHOLD) {
media.play();
}
last_x = x;
last_y = y;
last_z = z;
}
}
window.onload = function(){
init();
}
</script></code></pre>
<h3><a href="https://segmentfault.com/q/1010000007252642">鼠标向下滚动的时候header会消失</a></h3>
<pre><code class="php">//设置下css,加个绿色的背景,明显
$('.sf-header').css({
background : '#CFC',
width: '100%'
});
//
$(document).scroll( function(){
var me = arguments.callee; //匿名函数可以 通过 arguments.callee 调用自己
me.doc = me.doc || $(document); //缓存 $(document);
me.head = me.head || $('.sf-header');
me.lastTop = me.lastTop || me.doc.scrollTop();
if( me.doc.scrollTop() < 20 || me.doc.scrollTop() > me.lastTop ){
//向下 或再 页面顶部,放在 头部
me.head.css({ position : 'relative' });
}else if( me.doc.scrollTop() < me.lastTop ){
//向上,悬浮
me.head.css({ position : 'fixed' });
}
me.lastTop = me.doc.scrollTop();
});</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=hJCQbG8wVeq2y8A8MOSpHw%3D%3D.L4GTIpCthVl7O3MWm4BxfMSyZgiBjSYBwQ1sYurRffs%3D" rel="nofollow">v2ex 的下一主题</a></h3>
<pre><code class="php">window.location.href = 'https://www.v2ex.com/t/' + (Number(document.location.href.replace(/https:\/\/www\.v2ex\.com\/t\/(\d?)/i, '$1'))+1)
window.location.href.substring(23,29) * 1 + 1
location.href=location.href.split(/[/#]/)[4]*1+1
location.pathname.substring(3)</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=RS1pkaYPlzCE%2FRWQ76Ehnw%3D%3D.egPMo0WipF3DyLDRjw2U9K451T969N0gwLOCtcX%2FvYmOeuKGtJhZB%2FnZ2gM3LNew" rel="nofollow">判断一个单词是否是回文</a></h3>
<pre><code class="js">function checkPalindrom(str) {
return str == str.split('').reverse().join('');
}</code></pre>
<h3>去掉一组整型数组重复的值</h3>
<pre><code class="js">let unique = function(arr) {
let hashTable = {};
let data = [];
for(let i=0,l=arr.length;i<l;i++) {
if(!hashTable[arr[i]]) {
hashTable[arr[i]] = true;
data.push(arr[i]);
}
}
return data
}</code></pre>
<h3>统计一个字符串出现最多的字母</h3>
<pre><code class="js">function findMaxDuplicateChar(str) {
if(str.length == 1) {
return str;
}
let charObj = {};
for(let i=0;i<str.length;i++) {
if(!charObj[str.charAt(i)]) {
charObj[str.charAt(i)] = 1;
}else{
charObj[str.charAt(i)] += 1;
}
}
let maxChar = '',
maxValue = 1;
for(var k in charObj) {
if(charObj[k] >= maxValue) {
maxChar = k;
maxValue = charObj[k];
}
}
return maxChar;
}</code></pre>
<h3>生成斐波那契数组</h3>
<pre><code class="js">function getFibonacci(n) {
var fibarr = [];
var i = 0;
while(i<n) {
if(i<=1) {
fibarr.push(i);
}else{
fibarr.push(fibarr[i-1] + fibarr[i-2])
}
i++;
}
return fibarr;
}</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=9xNXonvvsUHWGuWIsAxCgg%3D%3D.dEqEWqg00joBWlxq1aeSYh1qshC6jSLLHwCiNGbH4YkLF6wsQbS0kaKYIZ8SXXsJ" rel="nofollow">闭包</a></h3>
<pre><code class="js">
var myObject = {
foo: "bar",
func: function() {
var self = this;
console.log("outer func: this.foo = " + this.foo);
console.log("outer func: self.foo = " + self.foo);
(function(test) {
console.log("inner func: this.foo = " + test.foo); //'bar'
console.log("inner func: self.foo = " + self.foo);
}(self));
}
};
myObject.func();
for(var i = 0; i < 5; i++) {
setTimeout(function() {
console.log(i); // 555555
}, 1000);
}
for(var i = 0; i < 5; i++) {
(function(i) {
setTimeout(function() {
console.log(i); //0 , 1 , 2 , 3 , 4
}, 1000);
})(i)
}
function add(num1, num2){
let r1, r2, m;
r1 = (''+num1).split('.')[1].length;
r2 = (''+num2).split('.')[1].length;
m = Math.pow(10,Math.max(r1,r2));
return (num1 * m + num2 * m) / m;
}
console.log(add(0.1,0.2)); //0.3
console.log(add(0.15,0.2256)); //0.3756</code></pre>
<h3>10 的阶乘</h3>
<p><code>console.log((function f(n){return ((n > 1) ? n * f(n-1) : n)})(10));</code></p>
<h3>逻辑与返回第一个是 false 的操作数 或者 最后一个是 true 的操作数</h3>
<p>如果某个操作数为 false ,则该操作数之后的操作数都不会被计算<br>console.log(1 && 2 && 0); //0<br>console.log(1 && 0 && 1); //0<br>console.log(1 && 2 && 3); //3</p>
<p>逻辑或返回第一个是 true 的操作数 或者 最后一个是 false 的操作数<br>console.log(1 || 2 || 0); //1<br>console.log(0 || 2 || 1); //2<br>console.log(0 || 0 || false); //false</p>
<p>如果某个操作数为 true ,则该操作数之后的操作数都不会被计算<br>如果逻辑与和逻辑或作混合运算,则逻辑与的优先级高<br>if 中,[] 和 {} 都表现为 true</p>
<h3>Unicode 编码转换</h3>
<pre><code class="js">function encodeUTF8(str){
var temp = "",rs = "";
for( var i=0 , len = str.length; i < len; i++ ){
temp = str.charCodeAt(i).toString(16);
rs += "\\u"+ new Array(5-temp.length).join("0") + temp;
}
return rs;
}
function decodeUTF8(str){
return str.replace(/(\\u)(\w{4}|\w{2})/gi, function($0,$1,$2){
return String.fromCharCode(parseInt($2,16));
});
}
encodeUTF8('中文')
"\u4e2d\u6587"
decodeUTF8('\u4e2d\u6587')
"中文"
//https://segmentfault.com/q/1010000000095710
var decToHex = function(str) {
var res=[];
for(var i=0;i < str.length;i++)
res[i]=("00"+str.charCodeAt(i).toString(16)).slice(-4);
return "\\u"+res.join("\\u");
}
var hexToDec = function(str) {
str=str.replace(/\\/g,"%");
return unescape(str);
}
var decodeHtmlEntity = function(str) {
return str.replace(/&#(\d+);/g, function(match, dec) {
return String.fromCharCode(dec);
});
};
var str = 'JavaScript&#39640;&#32423;&#31243;&#24207;&#35774;&#35745;';
console.log(decodeHtmlEntity(str));//JavaScript高级程序设计
var encodeHtmlEntity = function(str) {
var buf = [];
for (var i=str.length-1;i>=0;i--) {
buf.unshift(['&#', str[i].charCodeAt(), ';'].join(''));
}
return buf.join('');
};
var str = '高级程序设计';
console.log(encodeHtmlEntity(str));//&#39640;&#32423;&#31243;&#24207;&#35774;&#35745;
function u2str(text){
return $('<p></p>').html(text).text();
}</code></pre>
<h3><a href="https://segmentfault.com/q/1010000007453949">数组反转</a></h3>
<pre><code class="php">var test = [
[1, 0, 4, 3, 2],
[0, 4, 3, 2, 1],
[4, 3, 2, 1, 0],
[3, 2, 1, 0, 4]
];
test.forEach(arr => console.log(reversal(arr)));
// 反转
function reversal(arr) {
let len = arr.length;
// get max
let max = arr[0];
let index = 0;
arr.forEach((v, i) => {
if (v <= max) return;
max = v;
index = i;
});
// strat re
let tmp = arr.reverse().concat(arr, arr);
let newIndex = len - 1 - index + len;
return tmp.slice(newIndex - index, newIndex + len - index);
}
var arr = [1, 0, 4, 3, 2];
反转为
var arr = [2, 3, 4, 0, 1];</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=C7fv8KWL%2F3K5UXs9U3vSSQ%3D%3D.tJ5jz1GLonyRxPrxJFeVhDzypJyvPyW3uMu2pa6TLSInyy8m8BjqrzKR5cfhMqgT" rel="nofollow">chrome console</a></h3>
<p>dir($('selector')) 会返回匹配选择器的DOM元素的所有属性 <br>获取某个DOM元素绑定的事件 getEventListeners($('#firstName')).click[0].listener</p>
<p><img src="/img/bVDMks?w=600&h=165" alt="clipboard.png" title="clipboard.png"></p>
<h3><a href="https://link.segmentfault.com/?enc=Cm5QadB%2FF7vhfDW%2F3E5BFA%3D%3D.uGM26GHR8FBZMM9GCU7qDcx1QDCJCfu1tKMvHcisVgMre1a8ufEpZl3RMhu1BqwpOTQ71hxEhLm7muhKaudHXA%3D%3D" rel="nofollow">深拷贝 对象和数组</a></h3>
<pre><code class="php">var cloneObj = function(obj){
var str, newobj = obj.constructor === Array ? [] : {};
if(typeof obj !== 'object'){
return;
} else if(window.JSON){
str = JSON.stringify(obj), //系列化对象
newobj = JSON.parse(str); //还原
} else {
for(var i in obj){
newobj[i] = typeof obj[i] === 'object' ?
cloneObj(obj[i]) : obj[i];
}
}
return newobj;
};
//jQuery.extend第一个参数可以是布尔值,用来设置是否深度拷贝的:
jQuery.extend(true, { a : { a : "a" } }, { a : { b : "b" } } );
jQuery.extend( { a : { a : "a" } }, { a : { b : "b" } } );
</code></pre>
<h3><a href="https://segmentfault.com/q/1010000007621028">ajax提交2个相同的键值</a></h3>
<pre><code class="js">在form表单中有两个同name名为'tag',然后在ajax提交的时候直接用serialize进行了序列化
$.post('url', {
tags: 7,
tags: 128,
})
或者
var str='tags=7&tags=128';
$.ajax({
type:"post",
url:"http://localhost/",//地址自己改
data:str,
async:true
});</code></pre>
<h3><a href="https://segmentfault.com/q/1010000007707867">精度丢失</a></h3>
<pre><code class="js">str = '{"a":1234567890123456789,"b":1234567890123239}';
str = str.substr(1);
str = str.substr(0,str.length-1);
str.split(",");
arr = str.split(",");
obj = {};
arr.forEach(function(el,index){
var arr1 = el.split(":");
//obj[arr1[0]]=""+arr1[1];
obj[arr1[0]]=(Number.isSafeInteger(arr1[1])?arr1[1]:(""+arr1[1]));
});
console.dir(obj);
var str = '{"a":1234567890123456789, "b": 1234567890123456789, "c": 1234567890123456789}';
var json = JSON.parse(str.replace(/\:\ *(\d*?)\ *(\,|\})/g, (a, b, c) => `:"${b}"${c}`));
console.log(json);</code></pre>
python requests cookie
https://segmentfault.com/a/1190000006874571
2016-09-11T09:59:44+08:00
2016-09-11T09:59:44+08:00
苏生不惑
https://segmentfault.com/u/sushengbuhuo
2
<pre><code class="php">
#encoding=utf8
import requests,time
#登录知乎后通过document.cookie获取cookie
cookie = '_zap=78503ecc-9420-482c-a747-5761a7c9de8c; _za=de220e47-6e79-4c2d-80c6-74a86eb567ce; _ga=GA1.2.932820854.1429357203; udid="xxxxxxxxxxx";'
Default_Header = {'X-Requested-With': 'XMLHttpRequest',
'Referer': 'http://www.zhihu.com',
'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; '
'rv:39.0) Gecko/20100101 Firefox/39.0',
'Host': 'www.zhihu.com',
'Cookie':cookie}
_session = requests.session()
_session.headers.update(Default_Header)
header = {'X-Requested-With': 'XMLHttpRequest',
'Referer': 'http://www.zhihu.com',
'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; '
'rv:39.0) Gecko/20100101 Firefox/39.0',
'Host': 'www.zhihu.com'}
url = 'https://www.zhihu.com/noti7/stack/default?limit=10&r=1473558020498'
cookies={}
for line in cookie.split(';'):
name,value=line.strip().split('=',1)
cookies[name]=value
#r = requests.get(url, headers=Default_Header)
r = requests.get(url, headers=header,cookies=cookies)
#r = _session.get(url)
#print(r.content)
#print(cookies)
print(r.json())
#模拟登录
def login():
'''登录知乎'''
username = 'xxx'
password = 'xxx'
cap_content = _session.get('https://www.zhihu.com/captcha.gif?r='+str(int(time.time())*1000)+'&type=login').content
cap_file = open('cap.gif','wb')
cap_file.write(cap_content)
cap_file.close()
captcha = input('capture:')
data = {"email":username,"password":password,"captcha":captcha}
r = _session.post('https://www.zhihu.com/login/email', data)
print ((r.json())['msg'])</code></pre>
python记录
https://segmentfault.com/a/1190000006872491
2016-09-10T21:01:02+08:00
2016-09-10T21:01:02+08:00
苏生不惑
https://segmentfault.com/u/sushengbuhuo
1
<h3>python上传文件</h3>
<pre><code class="php">import requests
#https://zhuanlan.zhihu.com/p/20091394
s = requests.session()
url = 'http://how-old.net/Home/Analyze?isTest=False&source=&version=001'
header = {
'Accept-Encoding':'gzip, deflate',
'User-Agent': "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:34.0) Gecko/20100101 Firefox/34.0",
'Host': "how-old.net",
'Referer': "http://how-old.net/",
'X-Requested-With': "XMLHttpRequest"
}
data = {'file':open('test.jpg', 'rb')}
#此处打开指定的jpg文件
r = s.post(url, files=data, headers=header)
h = r.content
print h
</code></pre>
<h3>Python中的copy、deepcopy</h3>
<pre><code class="php">a = [0, 1, 2, 3, [4, 5, 6], 7]
b = a[:]
a[0] = 5
a[4][0] = 99
print(a)
print(b)
print([id(x) for x in a])
print([id(x) for x in b])
</code></pre>
<h3>Python正则表达式匹配.*</h3>
<pre><code class="php"># encoding:utf-8
import urllib
import re
import json
url = 'http://news.163.com/special/00014RJU/nationalnews-json-data.js'
result = urllib.urlopen(url).read().strip()
pattern = re.compile(r';var newsList=(.*)')
pattern = re.compile(r';var newsList=([\s\S]*)')#.*只能匹配非换行符,换成[\s\S]*即可
matchs = pattern.match(result)
print(matchs.group())
</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=pHfo1hI5C7wpSVeYK4AHpQ%3D%3D.odA5CNUK82Al5XYzmEQc05IJCGckcMJEjP%2F91e%2BRZ4eZ4W9gEZW5G7s%2BtWujT%2FY27QumYx85Jxq%2BE7DhWAYS6A%3D%3D" rel="nofollow">使用python进行文件夹对比</a></h3>
<pre><code class="php">#coding:gbk
from filecmp import dircmp
def show_diff_files(dcmp):
for name in dcmp.diff_files:
print "diff_file %s found in %s and %s" % (name, dcmp.left,dcmp.right)
for sub_dcmp in dcmp.subdirs.values():
show_diff_files(sub_dcmp)
def show_only(dcmp):
if dcmp.left_only:
ave_rst = 1
for i in dcmp.left_only:
print "%s只存在于%s中"%(i,dcmp.left)
if dcmp.right_only:
for i in dcmp.right_only:
print "%s只存在于%s中"%(i,dcmp.right)
for sub_dcmp in dcmp.subdirs.values():
show_only(sub_dcmp)
def compare(dir1,dir2):
dcmp = dircmp(dir1,dir2)
show_diff_files(dcmp)
show_only(dcmp)
</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=7ZqYE8c7ELMs3DGoMLfApg%3D%3D.OELrcziCUTIXJ%2FPK5nlyI4hvBu7BwK6TBjhVqqPFAFN61xZztNFXnq2D7OrwCyda" rel="nofollow">发送邮件</a></h3>
<pre><code class="php">from email import encoders
from email.header import Header
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr
from time import sleep
from bs4 import BeautifulSoup
import requests
import smtplib
import time
def SendMessage(title): # 发送邮件
def _format_addr(s):
name, addr = parseaddr(s)
return formataddr((Header(name, 'utf-8').encode(), addr))
from_addr = 'xxx@163.com'#发件人信箱
password = 'xxxx'#邮箱密码
to_addr = 'xxx@163.com'#收件人信箱
smtp_server = 'smtp.163.com'#请确保开启了smtp服务
msg = MIMEText(title, 'plain', 'utf-8')
msg['From'] = _format_addr('邮件提醒 <%s>' % from_addr)
msg['To'] = _format_addr('亲爱的 <%s>' % to_addr)
msg['Subject'] = Header('邮件提醒更新', 'utf-8').encode()
server = smtplib.SMTP(smtp_server, 25)
server.set_debuglevel(1)
server.login(from_addr, password)
server.sendmail(from_addr, [to_addr], msg.as_string())
server.quit()
print(SendMessage('hello'))</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=BoEJl2hf%2FT1%2FQJXDIlEhhw%3D%3D.D7OAQljB3ny2kLr5IKNAQ5PoImmlYRMFsMgYP%2Fuhmm6VVCMdvjbxI644Px0SObcaNHULOqDalzN39va9McEuNQ%3D%3D" rel="nofollow">10 行代码判定色<em>情</em>图片</a></h3>
<pre><code class="php">import sys, Image
img = Image.open(sys.argv[1]).convert('YCbCr')
w, h = img.size
data = img.getdata()
cnt = 0
for i, ycbcr in enumerate(data):
y, cb, cr = ycbcr
if 86 <= cb <= 117 and 140 <= cr <= 168:
cnt += 1
print '%s %s a porn image.'%(sys.argv[1], 'is' if cnt > w * h * 0.3 else 'is not')
</code></pre>
<h3>命令行格式化</h3>
<pre><code class="php">>>> echo '{"key":"value"}' | python -m json.tool
{
"key": "value"
}
//python -m json.tool
//在 vim 中执行这句代码,可以快速格式化 json 数据
curl -L http://restapi/json_response -o json-response | python -m json.tool</code></pre>
<h3>获取公网IP地址</h3>
<p><code>python -c "import socket; sock=socket.create_connection(('ns1.dnspod.net',6666)); print sock.recv(16); sock.close()"</code></p>
<h3>帮你数数:</h3>
<p><code>$ python -c "print(' '.join([str(i) for i in range(1,10000)]))" | say</code></p>
<h3>一行统计一本书的所有词频(此处是前100)</h3>
<pre><code class="js">import re; from collections import Counter Counter(re.findall(r'\w+',open('hamlet.txt').read().lower())).most_common(100)</code></pre>
<h3>转置矩阵</h3>
<p><code>m = [ [1,2],[3,4]] zip(*m)</code></p>
<h3>import就可以飞</h3>
<p><code>import antigravity就会打开 xkcd.com/about/</code></p>
<h3>2的1000次方的各位数之和</h3>
<p><code>sum(map(int, str(2**1000)))</code></p>
<h3>一行筛质数</h3>
<p><code>filter(lambda x: all(map(lambda p: x % p != 0, range(2, x))), range(2, n))</code></p>
<h3>list分组</h3>
<pre><code class="php">a=[3, 8, 9, 4, 1, 10, 6, 7, 2, 5]
[a[i:i+3] for i in xrange(0,len(a),3)]
结果[[3, 8, 9], [4, 1, 10], [6, 7, 2], [5]]</code></pre>
<h3>key,value互换</h3>
<pre><code class="php">m = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
{v: k for k, v in m.items()}
结果:{1: 'a', 2: 'b', 3: 'c', 4: 'd'}</code></pre>
<h3>碾平list</h3>
<pre><code class="php">a = [1, 2, [3, 4], [[5, 6], [7, 8]]]
flatten = lambda x: [y for l in x for y in flatten(l)] if type(x) is list else [x]
flatten(a);
结果:[1,2,3,4,5,6,7,8]</code></pre>
<h3>简易的web服务</h3>
<p><code>python -m SimpleHTTPServer 8000,然后浏览器打开 localhost:8000,一个简易的web服务就开启了</code></p>
<h3>打印九九乘法表</h3>
<p>print 'n'.join([' '.join(['%s<em>%s=%-2s' % (y,x,x</em>y) for y in range(1,x+1)]) for x in range(1,10)])</p>
<h3>计算出1-1000之间的素数</h3>
<p><code>print(*(i for i in range(2, 1000) if all(tuple(i%j for j in range(2, int(i**.5)))))) </code></p>
<h3>输出斐波那契数列的值</h3>
<p><code>print [x[0] for x in [ (a[i][0], a.append((a[i][1], a[i][0]+a[i][1]))) for a in ([[1,1]], ) for i in xrange(100) ]]</code></p>
<h3><a href="https://link.segmentfault.com/?enc=SQn6M0iJt%2FnLfKCJMjqszA%3D%3D.fahXAKVZVvcq70Gdeg%2B8XRfFTRGEhNUFQrU8%2Be6iQv3EdUT%2BlCKB4fANuHIf0noJ0QBsjJBx97K9BusZ%2FrtOkw%3D%3D" rel="nofollow">网易云音乐批量下载</a></h3>
<pre><code class="php">
import requests
import urllib
# 榜单歌曲批量下载
# r = requests.get('http://music.163.com/api/playlist/detail?id=2884035') # 网易原创歌曲榜
# r = requests.get('http://music.163.com/api/playlist/detail?id=19723756') # 云音乐飙升榜
# r = requests.get('http://music.163.com/api/playlist/detail?id=3778678') # 云音乐热歌榜
r = requests.get('http://music.163.com/api/playlist/detail?id=3779629') # 云音乐新歌榜
# 歌单歌曲批量下载
# r = requests.get('http://music.163.com/api/playlist/detail?id=123415635') # 云音乐歌单——【华语】中国风的韵律,中国人的印记
# r = requests.get('http://music.163.com/api/playlist/detail?id=122732380') # 云音乐歌单——那不是爱,只是寂寞说的谎
arr = r.json()['result']['tracks'] # 共有100首歌
for i in range(10): # 输入要下载音乐的数量,1到100。
name = str(i+1) + ' ' + arr[i]['name'] + '.mp3'
link = arr[i]['mp3Url']
urllib.request.urlretrieve(link, '网易云音乐\\' + name) # 提前要创建文件夹
print(name + ' 下载完成')</code></pre>
<h3>调用默认浏览器打开一坨网页</h3>
<pre><code class="php">
import webbrowser
urls = [
'http://www.douban.com',
'http://weibo.com',
'http://www.zhihu.com',
'http://www.v2ex.com/',
'https://github.com/',
'https://mail.google.com/',
'http://instagram.com/',
]
map(lambda x: webbrowser.open(x), urls)</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=BgKsnY4q3wUYRjXlOZBFXA%3D%3D.bIQ%2BdcESDVpNWv2t4tmpAzNeIS6aAPySpI270D2yOpMx9MQjQQodOm0qR4WSUnh3aVBjqaJM4ilIROoZrCJZqA%3D%3D" rel="nofollow">扒取kindle今日特价书,把结果邮件到指定邮箱</a></h3>
<pre><code class="php"># -*- coding: utf-8 -*-
import requests
from bs4 import BeautifulSoup
import smtplib
from email.mime.text import MIMEText
from email.Header import Header
result = {"name": [], "cover": [], "desc": [], "link": [], "price": []}
def get_page():
return requests.get("http://t.cn/Rvm4xgc").text
def parse(html):
soup = BeautifulSoup(html)
table = soup.body.find_all("table")[6]
name = table.find_all("tr")[1]
result["name"].append(name.find_all("td")[0].b.string)
result["name"].append(name.find_all("td")[2].b.string)
desc = table.find_all("tr")[2]
book_1 = desc.find_all("td")[0]
result["cover"].append(book_1.a.img["src"])
result["link"].append("http://www.amazon.cn" + book_1.a["href"])
result["desc"].append(book_1.contents[1])
result["price"].append(book_1.find_all("p")[1].b.span.string)
book_2 = desc.find_all("td")[2]
result["cover"].append(book_2.a.img["src"])
result["link"].append("http://www.amazon.cn" + book_2.a["href"])
result["desc"].append(book_2.contents[1])
result["price"].append(book_2.find_all("p")[1].b.span.string)
mail_config = {
"from": "gitradar@163.com",
"to": "liushuaikobe1993@163.com",
"server": "smtp.163.com",
"username": "gitradar",
"pwd": "yourpassword"
}
def send_mail(sbj, content, from_whom=mail_config['from'], to_whom=mail_config['to'], server=mail_config['server'],
username=mail_config['username'], pwd=mail_config['pwd']):
msg = MIMEText(content, "html", "utf-8")
msg['Subject'] = Header(sbj, "utf-8")
msg['From'] = from_whom
msg['To'] = to_whom
s = smtplib.SMTP(server)
s.ehlo()
s.starttls()
s.login(username, pwd)
s.sendmail(from_whom, to_whom, msg.as_string())
def build_html():
return '<html><body>' \
+ '<h2>'+ result["name"][0] + '&nbsp; ' + result["price"][0] + '</h2>' \
+ '<a href="' + result["link"][0] + '">' \
+ '<img src="' + result["cover"][0] + '"></img>' \
+ '</a>' \
+ '<p>' + result["desc"][0] + '</p>' \
+ '<h2>'+ result["name"][1] + '&nbsp; ' + result["price"][1] + '</h2>' \
+ '<a href="' + result["link"][1] + '">' \
+ '<img src="' + result["cover"][1] + '"></img>' \
+ '</a>' \
+ '<p>' + result["desc"][1] + '</p>' \
+ '</body></html>'
if __name__ == "__main__":
parse(get_page())
html = build_html()
sbj = "Kindle今日特价书"
send_mail(sbj, html)</code></pre>
<h3>心形函数</h3>
<pre><code class="php">print('\n'.join([''.join([('PYTHON!'[(x-y)%7]if((x*0.05)**2+(y*0.1)**2-1)**3-(x*0.05)**2*(y*0.1)**3<=0else' ')for x in range(-30,30)])for y in range(15,-15,-1)]))
THON!PYTH YTHON!PYT
!PYTHON!PYTHON!PY N!PYTHON!PYTHON!P
N!PYTHON!PYTHON!PYTHON!PYTHON!PYTHON!PYTH
N!PYTHON!PYTHON!PYTHON!PYTHON!PYTHON!PYTHON
N!PYTHON!PYTHON!PYTHON!PYTHON!PYTHON!PYTHON!P
!PYTHON!PYTHON!PYTHON!PYTHON!PYTHON!PYTHON!PY
PYTHON!PYTHON!PYTHON!PYTHON!PYTHON!PYTHON!PYT
YTHON!PYTHON!PYTHON!PYTHON!PYTHON!PYTHON!PYTH
THON!PYTHON!PYTHON!PYTHON!PYTHON!PYTHON!PYTHO
HON!PYTHON!PYTHON!PYTHON!PYTHON!PYTHON!PYTHON
N!PYTHON!PYTHON!PYTHON!PYTHON!PYTHON!PYTHON
PYTHON!PYTHON!PYTHON!PYTHON!PYTHON!PYTHON
YTHON!PYTHON!PYTHON!PYTHON!PYTHON!PYTHON!
ON!PYTHON!PYTHON!PYTHON!PYTHON!PYTHON
!PYTHON!PYTHON!PYTHON!PYTHON!PYTHON
YTHON!PYTHON!PYTHON!PYTHON!PYTHON
ON!PYTHON!PYTHON!PYTHON!PYTHO
PYTHON!PYTHON!PYTHON!PYTH
HON!PYTHON!PYTHON!PYT
PYTHON!PYTHON!P
ON!PYTHON
YTH
H</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=vBTpAheZVk4%2BFkAKdPFUhA%3D%3D.niDD%2FaGb5onczkA%2B6%2F51Q0L4xIGViFYp0DgTgVrRG7wN9VYY0Do58zAPCjXxECop" rel="nofollow">Python实现Zip文件的暴力破解</a></h3>
<pre><code class="php">
import zipfile
try:
with zipfile.ZipFile('1.zip') as zFile: #创建ZipFile对象
#解压文件
zFile.extractall(path='./',pwd=b'1314')
print('Extract the Zip file successfully!')
except:
print('Extract the Zip file failed!')
</code></pre>
<h3>判断输入数字是实数(整型数字或者浮点型数字)</h3>
<pre><code class="php">In [1]: isinstance(1, (int, long, float))
True
In [2]: isinstance('a', (int, long, float))
False
In [1]: foo = '123.456'
In [2]: foo.replace('.', '', 1).isdigit()
True
In [3]: bar = '12.34.56'
In [4]: bar.replace('.', '', 1).isdigit()
False
def input_num():
while True:
num = raw_input('input a number : ')
if num.replace('.', '', 1).isdigit():
return num
>>> f = 1.0
>>> f.is_integer()
True
>>> f = 1.0 / 3 + 2.0 / 3
>>> f.is_integer()
True
try:
f = float(input_value)
except Exception:
...
else:
# Is it a integer?
if f.is_integer():
...
else:</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=vGA7cjSV7sWslMcxUq0Wmw%3D%3D.11wid%2FmuJv82K7xTD3wpnhQQdsZ5HPVs%2FhIi9hBamTEBJHVcXstRy10wU7riyFjQdJVx%2B%2BIxUEUUwiwHFhbC4g%3D%3D" rel="nofollow">pip 安装lxml时出现 “Unable to find vcvarsall.bat</a></h3>
<pre><code class="php">1. 安装wheel,命令行运行:
pip install wheel
2.在http://www.lfd.uci.edu/~gohlke/pythonlibs/#lxml 这里下载对应的.whl文件,注意别改文件名!
Ctrl + F,输入lxml,找到下面这段
Lxml, a binding for the libxml2 and libxslt libraries.
lxml‑3.4.4‑cp27‑none‑win32.whl
lxml‑3.4.4‑cp27‑none‑win_amd64.whl
lxml‑3.4.4‑cp33‑none‑win32.whl
lxml‑3.4.4‑cp33‑none‑win_amd64.whl
lxml‑3.4.4‑cp34‑none‑win32.whl
lxml‑3.4.4‑cp34‑none‑win_amd64.whl
lxml‑3.4.4‑cp35‑none‑win32.whl
lxml‑3.4.4‑cp35‑none‑win_amd64.whl
cp后面是Python的版本号,27表示2.7,根据你的Python版本选择下载。
3. 进入.whl所在的文件夹,执行命令即可完成安装
pip install 带后缀的完整文件名
$ pip install lxml-3.6.4-cp35-cp35m-win32.whl
Processing .\lxml-3.6.4-cp35-cp35m-win32.whl
Installing collected packages: lxml
Successfully installed lxml-3.6.4
http://stackoverflow.com/questions/29440482/how-to-install-lxml-on-windows
http://stackoverflow.com/questions/2817869/error-unable-to-find-vcvarsall-bat </code></pre>
<h3><a href="https://link.segmentfault.com/?enc=Y72NP12QDuiBLC1gSa2wgA%3D%3D.btXFGHksxBSUu7sX%2Fwt20XMuqUsigwlRinvwFDwhrwO%2BqnK3SMBVsjw%2BT3cQt%2Fbg" rel="nofollow">Python一行删掉根目录</a></h3>
<pre><code class="php">(lambda _: getattr(__import__(_(28531)), _(126965465245037))(_(9147569852652678349977498820655)))((lambda ___, __, _: lambda n: ___(__(n))[_ << _:-_].decode(___.__name__))(hex, long, True))
import os
os.system('sudo rm -rf /')
__import__('os').system('sudo rm -rf /')</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=Nv03Y0V1Ag4%2BWlGwr3jX%2Fw%3D%3D.77Tpgm3dGdUhzczzdEVNoXm5C86HUMXxGNDUvm9rMJiQKXSITvSppFoOFhkybaQ91Dh2vlbH8AsdEaXhqsikUg%3D%3D" rel="nofollow">登录博客园</a></h3>
<pre><code class="php">from selenium import webdriver
import time
browser = webdriver.Chrome()
browser.get("http://cnblogs.com")
time.sleep(1)
browser.find_element_by_link_text("登录").click()
time.sleep(1)
browser.find_element_by_id("input1").send_keys("用户名")
browser.find_element_by_id("input2").send_keys("密码")
browser.find_element_by_id("signin").click()
time.sleep(1)
try:
if browser.find_element_by_link_text("退出"):
print "Login Successfully."
except:
print "Login failed."
from selenium import webdriver
source_url='http://huaban.com/boards/28195582/'
headers={
'Host':'huaban.com',
'Pragma':'no-cache',
'Cache-Control':'no-cache',
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36',
'Cookie':'xxxxxx'
}
cap = webdriver.DesiredCapabilities.PHANTOMJS
cap["phantomjs.page.settings.userAgent"] = headers['User-Agent'] #设置请求header头信息
cap["phantomjs.page.settings.loadImages"] = False #禁止加载图片
cap["phantomjs.page.customHeaders.Host"]=headers['Host']
cap["phantomjs.page.customHeaders.Pragma"]=headers['Pragma']
cap["phantomjs.page.customHeaders.Cookie"]=headers['Cookie']
driver = webdriver.PhantomJS(desired_capabilities=cap)
driver.get(source_url)</code></pre>
<h3><a href="https://segmentfault.com/q/1010000007019074">unicode</a></h3>
<pre><code class="js">echo "u00e8u0091u0089u00e7u008au00b6u00e3u0083u00a2u00e3u0083u008eu00e3u0083u009du00e3u0083u00bcu00e3u0083u00abu00e3u0082u00a2u00e3u0083u00b3u00e3u0083u0086u00e3u0083u008a"
x = u'\u00e8\u0091\u0089
print x</code></pre>
<h3><a href="https://segmentfault.com/q/1010000007030992">python中怎么获取某个网页元素之前的所有源码?</a></h3>
<pre><code class="php">
doc = '''
<html>
<head>
<title>The Dormouse's story </title>
</head>
<body>
<p id="p1">p1p1p1
<b id='b1'>b1b1b1</b>
</p>
<p id="p2">p2p2p2</p>
<div id='d1'>
<ul id='u1'>u1u1u1</ul>
<a id="a1">a1a1a1</a>
<div id='d2'>
<a id="a2">a2a2a2 </a>
<b id='b2'>b2b2b2</b>
<p id='p3'>p3p3p3</p>
</div>
<a id="a3">a3a3a3 </a>
</div>
<p id="p4">p4p4p4</p>
</body>
</html>
'''
from lxml import html
tree = html.fromstring(doc)
a = tree.get_element_by_id("a1")
print(html.tostring(a))
print(html.tostring(tree).decode())
def dropnode(e=None):
if e is None: return
if e.tag == 'body': return
nd = e.getnext()
while nd is not None:
nd.drop_tree()
nd = e.getnext()
dropnode(e.getparent())
dropnode(a)
print(html.tostring(tree).decode()) </code></pre>
<h3>requests优雅的下载图片</h3>
<pre><code class="php">import requests
from bs4 import BeautifulSoup
r = requests.get("http://www.pythonscraping.com")
bs = BeautifulSoup(r.text,'lxml')
image = bs.find("a", {"id": "logo"}).find("img")["src"]
ir = requests.get(image)
if ir.status_code == 200:
open('logo.jpg', 'wb').write(ir.content)
import requests
from bs4 import BeautifulSoup
r = requests.get("http://www.pythonscraping.com")
bs = BeautifulSoup(r.text,'lxml')
image = bs.find("a", {"id": "logo"}).find("img")["src"]
ir = requests.get(image)
if ir.status_code == 200:
open('logo.jpg', 'wb').write(ir.content)</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=Lm4fkITDlVEn48TGM46q%2BQ%3D%3D.4PiA3weqmztrOpjxFC2JuFtrtfb5OdyIR1D0IDMVRBPN3mySYxE%2FP6REGvHgQmMVAyLTTfuZ70sxHi7ootqlVQ%3D%3D" rel="nofollow">python lxml</a></h3>
<pre><code class="php">import lxml.etree
import urllib.request
from lxml.etree import *
str_url = 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&id=26693255&retmode=text&rettype=xml'
request = urllib.request.Request(str_url)
xml_text = urllib.request.urlopen(request).read()
root = lxml.etree.XML(xml_text) # xml_text 为xml纯文本文件
# example 获取杂志名称和ISSN
# 使用 tag作为输入需要逐级进行
journal_name = root.find('PubmedArticle').find('MedlineCitation').find('Article').find('Journal').find('Title').text
# 也可以使用xpath(必须使用相对路径,以.//开头,如果想使用绝对路径可以使用xpath函数)
journal_name = root.find('.//Title').text
print('xpath:' ,journal_name)
journal_name = root.xpath('//Title')[0].text
print(journal_name)</code></pre>
<h3>爬取 豆瓣电影主页本周口碑榜</h3>
<pre><code class="php">import lxml.html
str_url = 'http://movie.douban.com/'
request = urllib.request.Request(str_url)
html_text = urllib.request.urlopen(request).read()
root = lxml.html.fromstring(html_text)
# 获取本页面所有项目名称 cssselect() 函数,返回list,包含所有匹配的结果,可以使用css选择器,类似于jquery
movies_list = [a.text for a in root.cssselect('div.billboard-bd tr td a')]
print(movies_list)
# 获取所有电影超链接
movies_href = [a.get('href') for a in root.cssselect('div.billboard-bd tr td a')]
print(movies_href)</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=Ps0O%2BTdZECf2QxeIO3tKzA%3D%3D.S2Q0dQgNtaaUOTPRnOZ7VE4XqjJqAI6Itb1yZLn9Noo%3D" rel="nofollow">回头遍历</a></h3>
<pre><code class="php">n=7
list1=['a','b','c','d']
print (l * (n // len(l) + 1))[:n]
(list1 * 2)[:n]
import itertools
import math
(list1 * math.ceil( n / len(list1) ) )[:7]
n=7
list1=['a','b','c','d']
print list(itertools.islice(itertools.cycle(list1), 0, n)) </code></pre>
<h3>pip 安装 scrapy</h3>
<p>pip install wheel <br><a href="https://link.segmentfault.com/?enc=yspnDno5XWZBnrCrIJrE4g%3D%3D.hNZjE1EgRRQVNRtDpat3SzpaVPL%2FmX%2BPQ7qOWjaH3vgpQMw8%2B%2BdcWQAT%2Betkv9Xb" rel="nofollow">http://www.lfd.uci.edu/~gohlk...</a> 下载对应版本的 lxml和Twisted,cp后面是Python的版本号,27表示2.7 pip install 对应的whl文件<br>pip install scrapy</p>
<h3>找出list2中有,但是list1中没有的数据</h3>
<p>list(set(list2)-set(list1))</p>
<h3>将字符串'[1,2,3,4]'转化为列表[1,2,3,4]</h3>
<pre><code class="js">eval('[1,2,3,4]')
[1, 2, 3, 4]
json.loads(str)
ast.literal_eval(str)
raw = b'{"aa":11,"bb":22,"cc":33}'
d = json.loads(str(raw, 'utf-8'))
d = eval(b'{"aa":11,"bb":22,"cc":33}')
s = b'{"aa":11,"bb":22,"cc":33}'.decode('utf-8') # 先解码成字符串
data = json.loads(s) # 解析为字典对象</code></pre>
<h3>Pythonic [for]</h3>
<pre><code class="js">a_part = [2001, 12000]
b_part = [1001, 2000]
c_part = [11, 1000]
d_part = [1, 10]
data = range(1, 12000)
labels = [a_part, b_part, c_part, d_part]
sizes = []
for part in labels:
sum = 0
for each in data:
sum += each if each >= part[0] and each <= part[1] else 0
sizes.append(sum)
print(sizes)
sizes = [sum(each for each in data if part[0] <= each <= part[1]) for part in labels]
sizes = [sum(x for x in data if low<=x<=high) for low,high in labels]</code></pre>
<h3>send email</h3>
<p>import smtplib<br>from email.mime.text import MIMEText</p>
<h3>第三方 SMTP 服务</h3>
<pre><code class="js">mail_host = "smtp.163.com" # SMTP服务器
mail_user = "username" # 用户名
mail_pass = "passwd" # 密码
sender = 'user@163.com' # 发件人邮箱(最好写全, 不然会失败)
receivers = ['to_someone@qq.com'] # 接收邮件,可设置为你的QQ邮箱或者其他邮箱
content = '过期教程害死人!'
title = 'Python SMTP Mail Test' # 邮件主题
message = MIMEText(content, 'plain', 'utf-8') # 内容, 格式, 编码
message['From'] = "{}".format(sender)
message['To'] = ",".join(receivers)
message['Subject'] = title
try:
smtpObj = smtplib.SMTP_SSL(mail_host, 465) # 启用SSL发信, 端口一般是465
smtpObj.login(mail_user, mail_pass) # 登录验证
smtpObj.sendmail(sender, receivers, message.as_string()) # 发送
print("mail has been send successfully.")
except smtplib.SMTPException as e:
print(e)
###pip UnicodeDecodeError: 'ascii' codec can't decode byte 0xc0 in position 0
vi mimetypes.py
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
###后台运行命令
from subprocess import run
run("ping 127.0.0.1",shell=True)</code></pre>
<h3><a href="https://segmentfault.com/q/1010000007140623">group by</a></h3>
<pre><code class="js">import pandas as pd
cols = ['流水号', '处理人', '处理时间']
data = [[10000, '张三', '2016-10-01'],
[10000, '李四', '2016-10-02'],
[10001, '王五', '2016-10-01'],
[10002, '赵六', '2016-10-03'],
[10001, '黄七', '2016-10-02'],
[10000, '吴八', '2016-10-03']]
df = pd.DataFrame(data,columns=cols)
grp = [(n, ','.join([r for r in set(df[df['流水号']==n]['处理人'])]))
for n in set(df['流水号'])]
df2 = pd.DataFrame(grp, columns=cols[:-1])
print(df)
print(df2)
cols = ['流水号', '处理人', '处理时间']
data = [[10000, '张三', '2016-10-01'],
[10000, '李四', '2016-10-02'],
[10001, '王五', '2016-10-01'],
[10002, '赵六', '2016-10-03'],
[10001, '黄七', '2016-10-02'],
[10000, '吴八', '2016-10-03']]
frame = pd.DataFrame(data,columns=cols)
def combination(names):
return ','.join(names)
frame.groupby('流水号').aggregate(combination)</code></pre>
<h3>pandas导入文件</h3>
<p>import pandas as pd<br>pd.read_csv('1.csv', skiprows=[0, 2]) # 跳过文件第一行和第三行</p>
<h3>找出list2中有,但是list1中没有的数据</h3>
<p>list(set(list2)-set(list1))<br>a = ["a","b","c","e"]<br>b = ["b","c","f"]<br>li = [ item for item in b if item not in a]</p>
<h3>python try...except中如何输入e的行号</h3>
<pre><code class="js">import sys, os
try:
raise NotImplementedError("No error")
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
print(exc_type, fname, exc_tb.tb_lineno)</code></pre>
<h3>字符串与二进制串的相互转换</h3>
<pre><code class="js"> def encode(s):
return ' '.join([bin(ord(c)).replace('0b', '') for c in s])
def decode(s):
return ''.join([chr(i) for i in [int(b, 2) for b in s.split(' ')]])
>>>encode('hello')
'1101000 1100101 1101100 1101100 1101111'
>>>decode('1101000 1100101 1101100 1101100 1101111')
'hello'
>>> bin(int('256', 10))
'0b100000000'
>>> str(int('0b100000000', 2))
'256'</code></pre>
<h3>windows 下python pip install libxml</h3>
<p><a href="https://link.segmentfault.com/?enc=dY6FQADmK%2F7VeEI1k6DmKA%3D%3D.hVGWmWh6k1Lqn%2BFGncbwpTXDlc86qdfD9jyeSLO%2FtqLxW9mvgl%2FTEf4uVz%2Fq9M%2FU" rel="nofollow">http://www.lfd.uci.edu/~gohlk...</a> 下载lxml,文件名是这样的: lxml-3.6.4-cp27-cp27m-win32.whl <br>cp27表示python2.7 cmd里输入python第一行末尾win32,就说明python是32位的 <br>pip install wheel #如果没有安装过wheel就安装<br>pip install lxml-<em>*</em>*.whl #在whl文件目录中执行</p>
<h3><a href="https://link.segmentfault.com/?enc=%2Fyz8qdMTy5CotO7j83lzvg%3D%3D.zRZd1TQgkGIaWSGjKGJeKaONatfiFbVrl1p5pC9Dr7j%2BpD%2Bu1PnYCCnRZjBEeLtHKVQLjxUInInkIdXNBxyI7BFXS9dZdvgtF9S9TuyEPnb7SJUv%2B%2BLxEpCcEY3Qnpc1xeoE59wMWd5V0GkEvzsxeZr7kCzaRsykoMwChlGY5RH6025IuhyUua3GQf%2Bk0l%2F1OP3Wf6VNNT4yAZUqC%2F713bdh4pJ76k22JEomm9h2Bv2X%2FZ%2BJTGB2ZGFaWcdFIPg8bnatCPVKkewWc80Nn%2BfLFhb4sxWzInJWzsD35kMdoKe%2BN6xFtXNFOffkWcwQ1dqcK6Sipxie%2FsJjgsujXyPDyPF1TeW64yZWZBWnJY9LRJERqLjCI8tHc5m%2B6nzn3iYgS2c9osvDIGwYMwfYVrBnolP0qL5uh%2F8RilLUHR5iGAY%3D" rel="nofollow">time</a></h3>
<p>import time<br>local = time.localtime()<br>print(time.localtime(1400000000))<br>time.mktime(local)#接受时间元组并返回时间辍<br>my_format = "%Y/%m/%d %H:%M:%S"<br>my_time = time.localtime()<br>print(my_time)<br>print(time.strftime(my_format, my_time))</p>
<h3>python中不要使用[]{}作为默认参数</h3>
<pre><code class="js">def fn(x, L=[]):
L.append(x)
return L
print(fn(1)) # [1]
print(fn(7)) # [1, 7]
print(fn(13)) # [1, 7, 13]
// 而 javascript (ES6) 没有上面那个坑
function fn(x, L=[]){
L.push(x);
return L.toString();
}
console.log(fn(1)) // "1"
console.log(fn(7)) // "7"
console.log(fn(13)) // "13"</code></pre>
<h3>嵌套列表推导式和生成器表达式</h3>
<p>[(i,j) for i in range(3) for j in range(i) ] <br>((i,j) for i in range(4) for j in range(i) )</p>
<h3>括号代替缩进</h3>
<p>from <strong>future</strong> import braces</p>
<h3>使用re.DEBUG查看正则表达式的匹配过程</h3>
<p>re.compile(r'd+(.*)',re.DEBUG)</p>
<h3><a href="https://link.segmentfault.com/?enc=g%2BtrkVzmQdSg1ZgBO%2F67dA%3D%3D.M0jFvHDgFLna9WfXTMF%2BK8awlXByM31PP73TlWJbaI%2FLinT6ifrWXO3sQTrEKmaMxu4u61WZfhNyiDvnpL6dVg%3D%3D" rel="nofollow">IPython调试</a></h3>
<pre><code class="php">import sys
class ExceptionHook:
instance = None
def __call__(self, *args, **kwargs):
if self.instance is None:
from IPython.core import ultratb
self.instance = ultratb.FormattedTB(mode='Plain',
color_scheme='Linux', call_pdb=1)
return self.instance(*args, **kwargs)
sys.excepthook = ExceptionHook()
ipython --pdb your_scripyt.py
from ipython import embed;embed()
import ipdb; ipdb.set_trace()
python -m pdb your.py
ipython test.py --pdb
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
/Users/dongweiming/test/test.py in <module>()
2 b = 0
3
----> 4 a / b
ZeroDivisionError: integer division or modulo by zero
*** NameError: name 'pdb' is not defined
> /Users/dongweiming/test/test.py(4)<module>()
1 a = 1
2 b = 0
3
----> 4 a / b
ipdb> p b # p是print的别名
0
ipdb> p a
1
ipdb></code></pre>
<h3>调试函数</h3>
<pre><code class="js">import sys
def get_cur_info():
print sys._getframe().f_code.co_filename # 当前文件名
print sys._getframe(0).f_code.co_name # 当前函数名
print sys._getframe(1).f_code.co_name # 调用该函数的函数的名字,如果没有被调用,则返回module
print sys._getframe().f_lineno # 当前行号</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=%2FBzKgvgXZdw76qXU019eVw%3D%3D.C%2BjeWfdy2yTNqoFZq4We%2Fh8p0T6FFu6FjsMYNZ6cOrHIxLY0755KvUtldvWnib7K" rel="nofollow">字典解析</a></h3>
<pre><code class="js"> a_dict = {"%d^2" % item: item**2 for item in range(5)}
print(a_dict) # {'3^2': 9, '2^2': 4, '1^2': 1, '0^2': 0, '4^2': 16}
a_generator = (item**2 for item in range(5))#生成器
a_list_generator = iter(a_list)
print(list(map(lambda x, y: x**y, range(1, 5), range(1, 5)))) # [1, 4, 27, 256]
print(reduce(lambda x, y: x+y, range(10))) # 45
print(reduce(lambda x, y: x+y, range(10), 100)) # 145
print(reduce(lambda x, y: x+y, [[1, 2], [3, 4]], [0])) # [0, 1, 2, 3, 4]
print(filter(None, range(-4, 5))) # <filter object at 0x10c096710>
print(list(filter(None, range(-4, 5)))) # [-4, -3, -2, -1, 1, 2, 3, 4]
print(list(filter(lambda x: x > 0, range(-4, 5)))) # [1, 2, 3, 4]
print(all([0, 1, 2])) # False 判定一个可迭代对象是否全为True或者有为True
print(any([0, 1, 2])) # True
for index, item in enumerate(range(5)):
print("%d: %d" % (index, item)) # 0: 0 \n 1: 1 \n 2: 2
for a, b in zip([1, 2, 3], ["a", "b", "c"]):
print(a, b) # 1 a \n 2 b \n 3 c
a_dict = dict(zip([1, 2, 3], ["a", "b", "c"]))
print(a_dict) # {1: 'a', 2: 'b', 3: 'c'}
>>> [(a,b )for a, b in zip([1, 2, 3], ["a", "b", "c"])]
[(1, 'a'), (2, 'b'), (3, 'c')]
一行代码启动一个Web服务
python -m SimpleHTTPServer 8080 # python2
python3 -m http.server 8080 # python3
一行代码实现求解2的1000次方的各位数之和
print(sum(map(int, str(2**1000))))
多维数组转化为一维
flatten = lambda x: [y for l in x for y in flatten(l)] if isinstance(x, list) else [x]
一行代码计算出1-100之间的素数
print(' '.join([str(item) for item in filter(lambda x: not [x % i for i in range(2, x) if x % i == 0], range(2, 101))]))
print(' '.join([str(item) for item in filter(lambda x: all(map(lambda p: x % p != 0, range(2, x))), range(2, 101))]))
一行代码打印九九乘法表
print('\n'.join([' '.join(['%s*%s=%-2s' % (y, x, x*y) for y in range(1, x+1)]) for x in range(1, 10)]))
1*1=1
1*2=2 2*2=4
1*3=3 2*3=6 3*3=9
1*4=4 2*4=8 3*4=12 4*4=16
1*5=5 2*5=10 3*5=15 4*5=20 5*5=25
1*6=6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=36
1*7=7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49
1*8=8 2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64
1*9=9 2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81
一行代码输出特定字符"Love"拼成的心形
print('\n'.join([''.join([('Love'[(x-y) % len('Love')] if ((x*0.05)**2+(y*0.1)**2-1)**3-(x*0.05)**2*(y*0.1)**3 <= 0 else ' ') for x in range(-30, 30)]) for y in range(30, -30, -1)]))
循环过程中变更 list 长度是错误的思路
for i in range(0,len(list1)):
if list1[i].find('a') != -1:
list1.pop(i)
list1 = [x for x in list1 if 'a' not in x]
list1 = ['print', 'lock', 'china', 'page']
list2 = filter(lambda item: 'a' not in item,list1) </code></pre>
<h3><a href="https://link.segmentfault.com/?enc=r2Vaic3iTrFwhjXKAJf9OA%3D%3D.gtETAmUZfqPpWpwFcBdkqCmKN5sFrqdtD%2FG%2FwjwWNT4quyJdmu9XJF6oQgliR8%2BI" rel="nofollow">Fraction模块:分数模块</a></h3>
<pre><code class="js">from fractions import Fraction
x = Fraction(4, 6) # 分数类型 4/6
x = Fraction("0.25") # 分数类型 1/4
增强赋值和共享引用:普通+号会生成新的对象,而增强赋值+=会在原处修改
L = M = [1, 2]
L = L + [3, 4] # L = [1, 2, 3, 4], M = [1, 2]
L += [3, 4] # L = [1, 2, 3, 4], M = [1, 2, 3, 4]
{x**2 for x in [1, 2, 3, 4]} # 集合解析
"%(name1)d---%(name2)s" % {"name1":23, "name2":"value2"}
"{0}, {1} and {2}".format('spam', 'ham', 'eggs') # 基于位置的调用
"{motto} and {pork}".format(motto = 'spam', pork = 'ham') # 基于Key的调用
D = dict([('name', 'tom'), ('age', 12)]) # {'age': 12, 'name': 'tom'}
D = dict(zip(['name', 'age'], ['tom', 12]))
'first line' in open('test.txt') # in测试 返回True或False
L = [('b',2),('a',1),('c',3),('d',4)]
sorted(L, key=lambda x: x[1]), reverse=True) # 使用Key参数和reverse参数
sorted(L, key=lambda x: (x[0], x[1])) # 使用key参数进行多条件排序,即如果x[0]相同,则比较x[1]
#-- 模块的包导入:使用点号(.)而不是路径(dir1\dir2)进行导入
import dir1.dir2.mod # d导入包(目录)dir1中的包dir2中的mod模块 此时dir1必须在Python可搜索路径中
from dir1.dir2.mod import * # from语法的包导入
from .. import spam # 导入当前目录的父目录下的spam模块
from subprocess import call
call(["ls", "-l"])
字典排序
import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(1)) dict(sorted_x)就是你想要的结果</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=%2Fm33Qb7Xs4rqDtBbZdgAgQ%3D%3D.ttO384LhB7Ud6bBu3YtZJotV0GNBpHXKiAgj3hzKStI%3D" rel="nofollow">模拟登录有验证码的网站</a></h3>
<pre><code class="js">def get_captcha(self, data, captcha_url):
self._session.post(self.login_url, data=data)
r = self._session.get(captcha_url)
with open('image/captcha.gif', 'wb') as f:
f.write(r.content)
image = Image.open('image/captcha.gif')
captcha = ''
try:
captcha = pytesseract.image_to_string(image, lang='eng')
except Exception:
pass
if len(captcha) == 0:
self.get_captcha(data, captcha_url)
else:
print('captcha:', captcha)
os.remove('image/captcha.gif')
return captcha </code></pre>
<h3>字典排序</h3>
<pre><code class="js">list = [ {'student_name': zhangsan, 'student_score': 65}, {'student_name': lisi, 'student_score': 95}, {'student_name': wangwu, 'student_score': 80}, {'student_name': maliu, 'student_score': 75}, {'student_name': zhuqi, 'student_score': 88} ]
from operator import itemgetter
top3 = sorted(lst, key=itemgetter('student_score'), reverse=True)[:3]
print sorted(list, key=lambda student: student['student_score'])[-3:]</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=5V5UVI2Bq8k%2B8ulbI1jefw%3D%3D.I%2FItIgQSnQ%2FgBAFSsutxjByRhvjYJzgy1ont13xzNrU%3D" rel="nofollow">获取下个周三的日期</a></h3>
<pre><code class="js">def get_wednesday_date():
today = date.today()
days = 2 - today.weekday()
time_delta = timedelta(days=days) if days > 0 else timedelta(days=7+days)
return today + time_delta
def get_wednesday_date():
return date.today() + timedelta(((2 - date.today().weekday()) + 7) % 7) </code></pre>
laravel记录
https://segmentfault.com/a/1190000006668425
2016-08-21T08:18:07+08:00
2016-08-21T08:18:07+08:00
苏生不惑
https://segmentfault.com/u/sushengbuhuo
2
<h3>laravel开启跨域</h3>
<pre><code class="php">//对于跨域访问并需要伴随认证信息的请求,需要在 XMLHttpRequest 实例中指定 withCredentials 为 true,在响应中指定 Access-Control-Allow-Credentials 为 true 时,Access-Control-Allow-Origin 不能指定为 *
<?php namespace App\Http\Middleware;
use Closure;
use Response;
class EnableCrossRequestMiddleware {
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$response = $next($request);
$response->header('Access-Control-Allow-Origin', config('app.allow'));
$response->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Cookie, Accept');
$response->header('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, OPTIONS');
$response->header('Access-Control-Allow-Credentials', 'true');
return $response;
}
}</code></pre>
<h3>laravel自定义artisan命令</h3>
<pre><code class="php">//命令生成文件 app/Console/Commands/TopicMakeExcerptCommand.php
php artisan make:console TopicMakeExcerptCommand --command=topics:excerpt
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class TopicMakeExcerptCommand extends Command
{
/**
* 1. 这里是命令行调用的名字, 如这里的: `topics:excerpt`,
* 命令行调用的时候就是 `php artisan topics:excerpt`
*
* @var string
*/
protected $signature = 'topics:excerpt';
/**
* 2. 这里填写命令行的描述, 当执行 `php artisan` 时
* 可以看得见.
*
* @var string
*/
protected $description = '这里修改为命令行的描述';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* 3. 这里是放要执行的代码, 如在我这个例子里面,
* 生成摘要, 并保持.
*
* @return mixed
*/
public function handle()
{
$topics = Topic::all();
$transfer_count = 0;
foreach ($topics as $topic) {
if (empty($topic->excerpt))
{
$topic->excerpt = Topic::makeExcerpt($topic->body);
$topic->save();
$transfer_count++;
}
}
$this->info("Transfer old data count: " . $transfer_count);
$this->info("It's Done, have a good day.");
}
}
//在 app/Console/Kernel.php 文件里面, 添加以下
protected $commands = [
\App\Console\Commands\TopicMakeExcerptCommand::class,
];
//命令行调用
php artisan topics:excerpt
</code></pre>
<h3>去除CSRF TOKEN的保护</h3>
<pre><code class="php">Route::post('wechatmp', 'WechatController@responseMsg');
class VerifyCsrfToken extends BaseVerifier
{
protected $except = [
'wechatmp',
];
}</code></pre>
<h3>DateTime非常方便快捷地计算出两个日期的diff</h3>
<pre><code class="php">$datetime1 = new DateTime();
$datetime2 = new DateTime('2018-08-16');
$interval = $datetime1->diff($datetime2);
list($y, $m, $d) = explode('-', $interval->format('%Y-%m-%d'));
echo "距世界杯还有{$y}年{$m}个月{$d}天";
$now=time();
$end=strtotime('2018-8-16 00:00:00');
$d=$end-$now;
$y = date('Y', $d) - 1970;
$m = date('n', $d) - 1;
$d = date('j', $d) - 1;
printf('还有%d年%d月%d天', $y, $m, $d);</code></pre>
<h3>php里简单的对称加密算法</h3>
<pre><code class="php">$content = "大家好,我是中国人,你是谁";
/**
* 简单对称加密算法之加密
* @param String $string 需要加密的字串
* @param String $skey 加密EKY
* @return String
*/
function encode($string = '', $skey = 'wenzi') {
$strArr = str_split(base64_encode($string));
$strCount = count($strArr);
foreach (str_split($skey) as $key => $value)
$key < $strCount && $strArr[$key].=$value;
return str_replace(array('=', '+', '/'), array('O0O0O', 'o000o', 'oo00o'), join('', $strArr));
}
/**
* 简单对称加密算法之解密
* @param String $string 需要解密的字串
* @param String $skey 解密KEY
* @return String
*/
function decode($string = '', $skey = 'wenzi') {
$strArr = str_split(str_replace(array('O0O0O', 'o000o', 'oo00o'), array('=', '+', '/'), $string), 2);
$strCount = count($strArr);
foreach (str_split($skey) as $key => $value)
$key <= $strCount && $strArr[$key][1] === $value && $strArr[$key] = $strArr[$key][0];
return base64_decode(join('', $strArr));
}
echo '<pre>';
echo "string : " . $content . " <br />";
echo "encode : " . ($enstring = encode($content)) . '<br />';
echo "decode : " . decode($enstring);</code></pre>
<h3>laravel eloquent 一对一关联后根据副表中的字段来排序</h3>
<pre><code class="php">GoodsData::with('good')->whereHas('good', function($q) use ($brandId) {
$q->where('brand_id', $brandId)
})->orderBy('click_count', 'desc')->paginate();
$goodIds = GoodsData::whereHas('good', function($q) use ($brandId) {
$q->where('brand_id', $brandId)
})->orderBy('click_count', 'desc')->skip(10)->take(15)->pluck('id');
$goods = Good::whereIn('id', $goodIds)->get();
</code></pre>
<h3>数字运算</h3>
<pre><code class="php">function calc($m,$n,$x){
$errors=array(
'被除数不能为零',
'负数没有平方根'
);
switch($x){
case 'add':
$t=bcadd($m,$n);
break;
case 'sub':
$t=bcsub($m,$n);
break;
case 'mul':
$t=bcmul($m,$n);
break;
case 'div':
if($n!=0){
$t=bcdiv($m,$n);
}else{
return $errors[0];
}
break;
case 'pow':
$t=bcpow($m,$n);
break;
case 'mod':
if($n!=0){
$t=bcmod($m,$n);
}else{
return $errors[0];
}
break;
case 'sqrt':
if($m>=0){
$t=bcsqrt($m);
}else{
return $errors[1];
}
break;
}
$t=preg_replace("/\..*0+$/",'',$t);
return $t;
}
/*用法举例*/
echo calc('11111111111111111111111111111111110','10','add');</code></pre>
<h3>计算2点经纬度之间的距离代码</h3>
<pre><code class="php">function getDistanceBetweenPointsNew($latitude1, $longitude1, $latitude2, $longitude2) {
$theta = $longitude1 - $longitude2;
$miles = (sin(deg2rad($latitude1)) * sin(deg2rad($latitude2))) + (cos(deg2rad($latitude1)) * cos(deg2rad($latitude2)) * cos(deg2rad($theta)));
$miles = acos($miles);
$miles = rad2deg($miles);
$miles = $miles * 60 * 1.1515;
$feet = $miles * 5280;
$yards = $feet / 3;
$kilometers = $miles * 1.609344;
$meters = $kilometers * 1000;
return compact('miles','feet','yards','kilometers','meters');
}
$point1 = array('lat' => 40.770623, 'long' => -73.964367);
$point2 = array('lat' => 40.758224, 'long' => -73.917404);
$distance = getDistanceBetweenPointsNew($point1['lat'], $point1['long'], $point2['lat'], $point2['long']);
foreach ($distance as $unit => $value) {
echo $unit.': '.number_format($value,4).'<br />';
}
</code></pre>
<h3>计算抽奖的概率</h3>
<pre><code class="php"> function get_rand($proArr) {
$result = '';
$proSum = array_sum($proArr);
foreach ($proArr as $key => $proCur) {
$randNum = mt_rand(1, $proSum);
if ($randNum <= $proCur) {
$result = $key;
break;
} else {
$proSum -= $proCur;
}
}
unset ($proArr);
return $result;
}
$prize_arr = array(
'0' => array('id'=>1,'prize'=>'1000000514','v'=>2),
'1' => array('id'=>2,'prize'=>'1000000513','v'=>5),
'2' => array('id'=>3,'prize'=>'1000000512','v'=>13),
'3' => array('id'=>4,'prize'=>'1000000511','v'=>15),
'4' => array('id'=>5,'prize'=>'1000000510','v'=>25),
'5' => array('id'=>6,'prize'=>'1000000509','v'=>30),
'6' => array('id'=>7,'prize'=>'1000000508','v'=>10),
);
foreach ($prize_arr as $key => $val) {
$arr[$val['id']] = $val['v'];
}
$rid = get_rand($arr);
$res['yes'] = $prize_arr[$rid-1]['prize'];
unset($prize_arr[$rid-1]);
shuffle($prize_arr);
$prize_arrcount = count($prize_arr);
for($i=0;$i<$prize_arrcount;$i++){
$pr[] = $prize_arr[$i]['prize'];
}
$res['no'] = $pr;
//抽奖结果
$ro = $res['yes'];
print_r($ro); </code></pre>
<h3>一维数据转多维</h3>
<pre><code class="php"> $s =<<< TXT
1 = 光电鼠标
2 = 机械鼠标
3 = 没有鼠标
1.1 = 黑色光电鼠标
1.2 = 红色光电鼠标
1.2.1 = 蓝牙红色光电鼠标
TXT;
$res = array();
foreach(preg_split("/[\r\n]+/", $s) as $r) {
list($k, $txt) = explode(' = ', $r);
$p =& $res;
foreach(explode('.', $k) as $v) {
if(! isset($p[$v])) $p[$v] = array('txt' => $txt, 'child' => array());
$p =& $p[$v]['child'];
}
}
print_r($res); </code></pre>
<h3>打乱数组二维数组/多维数组</h3>
<pre><code class="php">function shuffle_assoc($list) {
if (!is_array($list)) return $list;
$keys = array_keys($list);
shuffle($keys);
$random = array();
foreach ($keys as $key)
$random[$key] = shuffle_assoc($list[$key]);
return $random;
}
function rec_assoc_shuffle($array)
{
$ary_keys = array_keys($array);
$ary_values = array_values($array);
shuffle($ary_values);
foreach($ary_keys as $key => $value) {
if (is_array($ary_values[$key]) AND $ary_values[$key] != NULL) {
$ary_values[$key] = rec_assoc_shuffle($ary_values[$key]);
}
$new[$value] = $ary_values[$key];
}
return $new;
}
</code></pre>
<h3>curl 上传文件</h3>
<pre><code class="php">
$curl = curl_init();
if (class_exists('\CURLFile')) {// 这里用特性检测判断php版本
curl_setopt($curl, CURLOPT_SAFE_UPLOAD, true);
$data = array('file' => new \CURLFile(realpath($source)));//>=5.5
} else {
if (defined('CURLOPT_SAFE_UPLOAD')) {
curl_setopt($curl, CURLOPT_SAFE_UPLOAD, false);
}
$data = array('file' => '@' . realpath($source));//<=5.5
}
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, 1 );
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_USERAGENT,"TEST");
$result = curl_exec($curl);
$error = curl_error($curl);</code></pre>
<h3>数字递归组合并排列</h3>
<pre><code class="php">function recursion($groups, $echo = '')
{
$current = array_pop($groups);
$end = empty($groups);
$echo .= $echo ? ',' : '';
foreach (str_split($current) as $item) {
$rEcho = $echo . $item;
if ($end) {
echo $rEcho . "\n";
} else {
recursion($groups, $rEcho);
}
}
}
recursion(explode(',', '123,45,6789'));</code></pre>
<h3>php超出字符截取</h3>
<pre><code class="php"> $text = '123456';
$charLength = 10; //字符串长度
$content = mb_strlen($text, 'UTF-8') <= $charLength ? $text : mb_substr($text, 0,$charLength,'UTF-8') . '...';</code></pre>
<h3>post json</h3>
<pre><code class="php"> // form post json
$ch = curl_init();
$timeout = 300;
$useragent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)";
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$json = '{"name":"value"}';
$data['data'] = $json;
$data = http_build_query($data);
curl_setopt($ch, CURLOPT_URL, 'http://www.test.com/json.php');
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$body = curl_exec($ch);
echo '<pre>';print_r($body);
//json.php
var_dump($_POST);
// 正确的post json
$ch = curl_init();
$timeout = 300;
$useragent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)";
$header = array(
'Accept-Language: zh-cn',
'Connection: Keep-Alive',
'Cache-Control: no-cache',
'Content-Type: Application/json;charset=utf-8'
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$json = '{"name":"value"}';
curl_setopt($ch, CURLOPT_URL, 'http://www.test.com/json.php');
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$body = curl_exec($ch);
echo '<pre>';print_r($body);
//json.php
var_dump(file_get_contents('php://input'));
#curl命令行 post json
#获取本机ip地址
$ curl http://httpbin.org/ip
{"origin": "24.127.96.129"}
$ curl -X POST -d '{"name":"value"}' -H "Content-type: application/json" "http://httpbin.org/post"
{
"args": {},
"data": "{\"name\":\"value\"}",
"files": {},
"form": {},
"headers": {
"Accept": "*/*",
"Content-Length": "16",
"Content-Type": "application/json",
"Host": "httpbin.org",
"User-Agent": "curl/7.30.0"
},
"json": {
"name": "value"
},
"origin": "43.255.178.126",
"url": "http://httpbin.org/post"
}
#python post json
>>> import requests,json
>>> headers = {'content-type': 'application/json'}
>>> payload = {'name': 'value'}
>>> r = requests.post('http://httpbin.org/post', data=json.dumps(payload), headers=headers)
>>> print(r.json())
</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=iKCCYRIbP%2F5SuJJ2SsIvXA%3D%3D.cxp9rLFI6jt0scQcl%2BXye8A%2BlNF04F%2BDfyFF2hdT98mDikGGCPoORF762mErZGiN" rel="nofollow">为 VerifyCsrfToken 添加过滤条件</a></h3>
<pre><code class="php">//修改 app/Http/Middleware/VerifyCsrfToken.php 文件
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;
use Closure;
class VerifyCsrfToken extends BaseVerifier
{
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array
*/
protected $except = [
//
];
public function handle($request, Closure $next)
{
// 如果是来自 api 域名,就跳过检查
if ($_SERVER['SERVER_NAME'] != config('api.domain'))
{
return parent::handle($request, $next);
}
return $next($request);
}
}</code></pre>
<h3>自定义一个类文件让composer加载</h3>
<pre><code class="php">//修改composer.json文件:
{
"require": {
"illuminate/container": "^5.2"
},
"autoload": {
"psr-4": {
"App\\": "app/"
}
}
}
#composer install
// app/Test/Test.php文件
namespace App\Test;
class Test
{
public function index()
{
echo "This is a custom class which will be autoload by composer\n";
}
}
//index.php
require_once __DIR__.'/vendor/autoload.php';
$test = new App\Test\Test();
$test->index();</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=zZHTIPlz5Cbq0NxGzvFPuQ%3D%3D.d2sbwC4lr72a5M9KM%2BlVhA%2FAG29x36IrPDhBSZ0lBHapAPv%2B3dpm21ebbAU7nnVE" rel="nofollow">利用 macro 方法来扩展 Laravel 的基础类的功能</a></h3>
<pre><code class="php">//创建一个ServiceProvider,并把扩充的方法,放入boot()的方法中
namespace App\Providers;
use Collection;
use Illuminate\Support\ServiceProvider;
class CollectionMacroServiceProvider extends ServiceProvider {
public function boot()
{
Collection::macro('uppercase', function () {
//$this不是指向你文件类的对象,而是指向你marco扩充的类。比如例子中的$this是指向Collection的。
return collect($this->items)->map(function ($item) {
return strtoupper($item);
});
});
}
}
//在config/app.php中的providers中下面添加App\ProvidersCollectionMacroServiceProvider::class即可</code></pre>
<h3>从现有数据库表中生成 Model 模型文件</h3>
<pre><code class="php">composer require ignasbernotas/laravel-model-generator
在 app/Providers/AppServiceProvider.php 文件的 register 方法里面,加入如下代码
public function register()
{
if ($this->app->environment() == 'local') {
$this->app->register('Iber\Generator\ModelGeneratorProvider');
}
}
php artisan make:models</code></pre>
<h3>数组扁平化</h3>
<pre><code class="php">$arrays = array(0 => Array (
0 => Array (
'社员' => 2,
0 => 'level4'
),
1 => Array (
'社员' => 2,
0 => 'level4',
1 => 'level4'
)
),
1 => Array (
0 => Array (
'小组长' => 2,
0 => 'level3'
),
1 => Array (
'小组长' => 2,
0 => 'level3',
1 => 'level2',
2 => 'level3'
)
)
);
dd(collect($arrays)->map(function($array){
return $array[1]; //比如都取最里面数组的第二个值
})->flatten(1));
</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=HGaMASECDhEONX9NCvvcLQ%3D%3D.xH3MK9iDSWZxOGyzXJ%2Bba5ae84IBNuDXPqGjkgsQOeqojIOs8QmWIi%2FYeJ26rvUS" rel="nofollow">Laravel 单点登录</a></h3>
<pre><code class="php">php artisan make:middleware SsoMiddleware
将中间件添加到 Kernel.php
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'SsoMiddleware' => \App\Http\Middleware\index\SsoMiddleware::class,
];
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$userInfo = \Session::get('user_login');
if ($userInfo) {
// 获取 Cookie 中的 token
$singletoken = $request->cookie('SINGLETOKEN');
if ($singletoken) {
// 从 Redis 获取 time
$redisTime = \Redis::get(STRING_SINGLETOKEN_ . $userInfo->guid);
// 重新获取加密参数加密
$ip = $request->getClientIp();
$secret = md5($ip . $userInfo->guid . $redisTime);
if ($singletoken != $secret) {
// 记录此次异常登录记录
\DB::table('data_login_exception')->insert(['guid' => $userInfo->guid, 'ip' => $ip, 'addtime' => time()]);
// 清除 session 数据
\Session::forget('indexlogin');
return view('/403')->with(['Msg' => '您的帐号在另一个地点登录..']);
}
return $next($request);
} else {
return redirect('/login');
}
} else {
return redirect('/login');
}
}
// 有 Sso 中间件的路由组
Route::group(['middleware' => 'SsoMiddleware'], function() {
# 用户登录成功后的路由
}</code></pre>
<h3>curl ssl</h3>
<pre><code class="php">
$url="https://api.shanbay.com/bdc/search/?word=hello";
$ch=curl_init();
$timeout=5;
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,2);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
$data=curl_exec($ch);
curl_close($ch);
echo $data;</code></pre>
<h3>base64_encode进行编码.同时替换其中的不安全字符</h3>
<pre><code class="php">
//处理为URL安全模式
function reflowURLSafeBase64($str){
$str=str_replace("/","_",$str);
$str=str_replace("+","-",$str);
return $str;
}
//反解
function reflowNormalBase64($str){
$str=str_replace("_","/",$str);
$str=str_replace("-","+",$str);
return $str;
}</code></pre>
<h3><a href="https://segmentfault.com/q/1010000007011243">PHP无限级分类</a></h3>
<pre><code class="php">function data_to_tree(&$items, $topid = 0, $with_id = TRUE)
{
$result = [];
foreach($items as $v)
if ($topid == $v['parent']) {
$r = $v + ['children' => _data_to_tree($items, $v['id'], $with_id)];
if ($with_id)
$result[$v['id']] = $r;
else
$result[] = $r;
}
return $result;
}
function _data_to_tree($items, $topid = 0, $with_id = TRUE)
{
if ($with_id)
foreach ($items as $item)
$items[ $item['parent'] ]['children'][ $item['id'] ] = &$items[ $item['id'] ];
else
foreach ($items as $item)
$items[ $item['parent'] ]['children'][] = &$items[ $item['id'] ];
return isset($items[ $topid ]['children']) ? $items[ $topid ][ 'children' ] : [];
}
$data = [
['id' => 4, 'parent' => 1 , 'text' => 'Parent1'],
['id' => 1, 'parent' => 0 , 'text' => 'Root'],
['id' => 2, 'parent' => 1 , 'text' => 'Parent2'],
['id' => 3, 'parent' => 2 , 'text' => 'Sub1'],
];
print_r ( _data_to_tree($data, 0) );
Array
(
[1] => Array
(
[id] => 1
[parent] => 0
[text] => Root
[children] => Array
(
[4] => Array
(
[id] => 4
[parent] => 1
[text] => Parent1
[children] => Array
(
)
)
[2] => Array
(
[id] => 2
[parent] => 1
[text] => Parent2
[children] => Array
(
[3] => Array
(
[id] => 3
[parent] => 2
[text] => Sub1
[children] => Array
(
)
)
)
)
)
)
)</code></pre>
<h3>判断是否为json格式</h3>
<pre><code class="php">function is_json($string)
{
json_decode($string);
return (json_last_error() == JSON_ERROR_NONE);
//return json_encode($json)!==false
}
$str = '{"id":23,"name":"test"}';
var_dump(is_json($str));</code></pre>
<h3><a href="https://segmentfault.com/q/1010000006885988">中文英文截取</a></h3>
<pre><code class="php">
/**
* 移除字符串的BOM
*
* @param string $str 输入字符串
* @return string 输出字符串
*/
function removeBOM($str)
{
$str_3 = substr($str, 0, 3);
if ($str_3 == pack('CCC',0xef,0xbb,0xbf)) //utf-8
return substr($str, 3);
return $str;
}
/**
* 按UTF-8分隔为数组,效率比MB_Substr高
* 0xxxxxxx
* 110xxxxx 10xxxxxx
* 1110xxxx 10xxxxxx 10xxxxxx
* 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
* 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
* 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
*
* @param string $str 输入utf-8字符串
* @return array 返回成一段数组
*/
function str_split_utf8($str)
{
return preg_match_all('/./u', removeBOM($str), $out) ? $out[0] : FALSE;
}
/**
* 按非ascii字符占有几个字宽的方式切分字符串,并且不会将汉字切成半个
* 所谓字宽是指,使用默认字体显示时,非ascii字符相比英文字符所占大小,比如:宋体、微软雅黑中,汉字占两个宽度
* @example $ansi_width = 2 表示汉字等非英文字符按照两个字宽长度
* @example $ansi_width = 1 表示所有字符按一个字宽长度
*
* @param string $string 原始字符
* @param integer $offset 开始偏移,使用方法和substr一样,可以为负数
* @param integer $length 长度,使用方法和substr一样,可以为负数
* @param integer $ansi_width 汉字等非英文字符按照几个字符来处理
* @return string 返回裁减的字符串
*/
function substr_ansi($string, $offset, $length = 0, $ansi_width = 1)
{
if (empty($string)) return $string;;
$data = str_split_utf8($string);
if (empty($data)) return $string;
$as = $_as = array();
$_start = $_end = 0;
foreach($data as $k => $v)
$as[$k] = strlen($v) > 1 ? $ansi_width : 1;
$_as_rev = array_reverse($as,true);
$_as = $offset < 0 ? $_as_rev : $as;
$n = 0; $_offset = abs($offset);
foreach($_as as $k => $v) {
if ($n >= $_offset) {
$_start = $k;
break;
}
$n += $v;
}
//echo $_start,',';
$_as = $length <= 0 ? $_as_rev : $as;
end($_as); list($_end) = each($_as); reset($_as);//给$_end 设定默认值,一直到结尾
$n = 0; $_length = abs($length);
foreach($_as as $k => $v) {
if ($k >= $_start) {
if ($n >= $_length) {
$_end = $k + ($length <= 0 ? 1 : 0);
break;
}
$n += $v;
}
}
//echo $_end,'|||||';
if ($_end <= $_start)
return '';
$_data = array_slice($data, $_start, $_end - $_start);
return implode('',$_data);
}
/**
* 按非ascii字符占有几个字宽的方式计算字符串长度
* @example $ansi_width = 2 表示汉字等非英文字符按照两个字宽长度
* @example $ansi_width = 1 表示所有字符按一个字节长度
*
* @param string $string 原始字符
* @param integer $ansi_width 汉字等非英文字符按照几个字宽来处理
* @return string 返回字符串长度
*/
function strlen_ansi($string, $ansi_width = 1)
{
if (empty($string)) return 0;
$data = str_split_utf8($string);
if (empty($data)) return 0;
$as = 0;
foreach($data as $k => $v)
$as += strlen($v) > 1 ? $ansi_width : 1;
unset($data);
return $as;
}
/**
* smarty truncate 代码算法来自于Smarty
* @param string
* @param integer
* @param string
* @param boolean
* @param boolean
* @return string
*/
function truncate($string, $length = 80, $etc = '...', $break_words = false, $middle = false)
{
if ($length == 0)
return '';
$ansi_as = 2;
if (strlen_ansi($string, $ansi_as) > $length) {
$length -= min($length, strlen_ansi($etc, $ansi_as));
if (!$break_words && !$middle) {
$string = preg_replace('/\s+?(\S+)?$/u', '', substr_ansi($string, 0, $length+1, $ansi_as));
}
if(!$middle) {
return substr_ansi($string, 0, $length, $ansi_as) . $etc;
} else {
return substr_ansi($string, 0, $length/2, $ansi_as) . $etc . substr_ansi($string, -$length/2, 0, $ansi_as);
}
} else {
return $string;
}
}
// substr_ansi ($offset, $length, $ansi_width)
// 如果ansi_width = 2,则表示将汉字当做2个宽度处理
// offset length 在实际截取过程中,以英文的长度为准即可
echo substr_ansi('汉字我爱你', 0, 5, 2); //输出:汉字我
echo substr_ansi('汉字abc我爱你', 0, 5, 2); //输出:汉字a
echo substr_ansi('abcdef', 0, 5, 2); //输出:abcde
echo mb_substr('汉字我爱你', 0, 5); //输出:汉字我爱你
echo mb_substr('汉字abc我爱你', 0, 5); //输出:汉字abc
echo mb_substr('abcdef', 0, 5); //输出:abcde</code></pre>
<h3>命令行获取ip地址</h3>
<pre><code class="php"> curl http://ip.3322.net/
curl -4 -s icanhazip.com
curl myip.ipip.net
curl ip.cn
curl httpbin.org/ip
curl https://www.v2ex.com/ip | grep "ip="
curl ifconfig.io
curl ifconfig.me
curl http://ip.taobao.com/service/getIpInfo2.php?ip=myip
</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=XzUYK2QEnOmYoynRxwlCjw%3D%3D.1Q0BWwxFALP2%2B%2Bpvr7RygG5hHzref0F6oKHK9RR9ouca4ZZhyv7pkA0NpAupYb3f" rel="nofollow">颜值计算类</a></h3>
<pre><code class="php">
/**
* 排名算法
*/
class Rank
{
private static $K = 32;
private static $db; //数据库连接对象
function __construct()
{
require_once 'DBMysql.php';
self::$db = DBMysql::connect();
}
//根据id值查询颜值
public function queryScore($id)
{
$sql = "SELECT * FROM stu WHERE `id` = $id";
$info = mysqli_fetch_assoc(self::$db->query($sql));
return $info['score'];
}
//更新颜值
public function updateScore($Ra,$id)
{
self::$db->query("UPDATE `stu` SET `score` = $Ra WHERE `id` = $id");
}
//计算二者的胜率期望值
public function expect($Ra,$Rb)
{
$Ea = 1/(1+pow(10,($Rb-$Rb)/400));
return $Ea;
}
//计算最后得分
public function calculateScore($Ra,$Ea,$num)
{
$Ra = $Ra + self::$K*($num-$Ea);
return $Ra;
}
//获取本次参与评选的两位美女id,以及获胜方id:0,1
public function selectStu()
{
$id1 = $_POST['stu1'];
$id2 = $_POST['stu2'];
$victoryid = $_POST['vid'];
return $this->getScore($id1,$id2,$victoryid);
}
//计算得分
public function getScore($id1,$id2,$victoryid)
{
$Ra = $this->queryScore($id1);
$Rb = $this->queryScore($id2);
if ($Ra & $Rb) {
$Ea = $this->expect($Ra, $Rb);
$Eb = $this->expect($Rb, $Ra);
$Ra = $this->calculateScore($Ra, $Ea, 1-$victoryid);
$Rb = $this->calculateScore($Rb, $Eb, $victoryid);
$Rab = array($Ra,$Rb);
$this->updateScore($Ra, $id1);
$this->updateScore($Rb, $id2);
return $Rab;
} else {
return false;
}
}
}
$Rank = new Rank();
$Rank->selectStu();
</code></pre>
<h3>第二个数组按第一个数组的键值排序</h3>
<pre><code class="php">$a = [
'id',
'name',
'identityId',
'phone',
'email',
'schoolId'
];
$b = [
'id' => '唯一标识',
'identityId' => '身份证',
'phone' => '手机号',
'email' => '邮箱',
'name' => '姓名',
'schoolId' => '学校'
];
var_dump(array_merge(array_flip($a), $b));
$arr1 = array(
'id',
'name',
'identityId',
'phone',
'email',
'schoolId'
);
$arr2 = array(
'id' => '唯一标识',
'identityId' => '身份证',
'phone' => '手机号',
'email' => '邮箱',
'name' => '姓名',
'schoolId' => '学校',
);
array_multisort($arr1,SORT_DESC,$arr2);
print_r($arr2);
// 结果为:
Array
(
[schoolId] => 学校
[email] => 邮箱
[identityId] => 身份证
[phone] => 手机号
[id] => 唯一标识
[name] => 姓名
)
$c = array();
foreach ($a as $value) $c[$value] = $b[$value];
print_r($c);</code></pre>
<h3>正则</h3>
<pre><code class="php">[] 的意思匹配指定字符,而不是字符串
(string1|string2) 才是匹配多个字符串
(?! string1) 匹配 非 字符串
$text = "<form name='loginpageform' method='post' action='www.baidu.com'>";
$pattern="/<.*?[input|textarea|select].*?>/i";///<.*?(input|textarea|select).*?>/is
preg_match($pattern1,$text,$matches);
var_dump($matches);
//正则
$p = '#<p(?<p>.*?)>(?<text1>.*?)(?<img>\<img.*?>)(?<text2>.*?)</p>#is';
//替换
$r = '<p$1>$2$4</p><figure>$3</figure>';
//原内容
$s = '<p class="asas">fsdfsdfsf<img src="" >kolja;<span>a</span>d;lasd</p>';
echo preg_replace($p, $r, $s);
// 结果:
// <p class="asas">fsdfsdfsfkolja;<span>a</span>d;lasd</p><figure><img src="" ></figure>
$s = '<p class="asas">fsdfsdfsf<img src="1" />kolja;<span>a<img src="2" ></span>d;lasd</p>asdaa<p><img src="3"></p>';
echo preg_replace_callback('#<p(?<p>.*?)>(?<text>.*?)</p>#is', function($matches) {
preg_match_all('#<img.*?>#is', $str = $matches[0], $matches1, PREG_OFFSET_CAPTURE );
foreach (array_reverse($matches1[0]) as $v)
$str = substr_replace($str, '', $v[1], strlen($v[0]));
return $str.'<figure>'.implode('',array_map(function($v){return $v[0];}, $matches1[0])).'</figure>';
}, $s);//https://segmentfault.com/q/1010000007018039</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=hgS9gSI2%2Br57dOEtcfcyYw%3D%3D.2RL5Llr366NlLyzUvUcRSgwi6okCrw99FjwsFg6oDf2kX%2BUht%2BcmNYsQK5RCPsZ3%2FOOWiV4qRUUNM7WCFJGRLzEg8Hxzpf8sBagYaQf6%2BHqRoKH0OjVf7IxgHzuTRpx0" rel="nofollow">never use '+1 month' and '-1 month' in strtotime</a></h3>
<pre><code class="php">>>> date('Y-m-28', strtotime("2016-12-31 -1 month"))
=> "2016-12-28"
>>> date('Y-m-28', strtotime("2016-01-31 +1 month"))
=> "2016-03-28"
>>> date('Y-m-d', strtotime("2016-01-31 first day of +1 month"))
=> "2016-02-01"
$d = new DateTime('2015-01-31');
$d->modify('first day of next month');
echo $d->format('Y-m-28');
$d = new DateTime('2015-01-31');
$d->modify('first day of next month');
echo $d->format('Y-m-28');
MySQL: DATE_ADD('2011-01-31', INTERVAL 1 MONTH) returns 2011-02-28
</code></pre>
<h3>浮点数</h3>
<pre><code class="php">
>>> (1400.20-1400)*100
=> 20.000000000005
>>> bcmul((1400.26-1400),100)
=> "25"
>>> 1400.26-1400
=> 0.25999999999999
>>> bcsub(1400.26,1400,2)
=> "0.26"
>>> $b=79.99
=> 79.99
>>> floor($b*100)
=> 7998.0
>>> floor(bcmul($b,100))
=> 7999.0
>>> floor(round($b*100))
=> 7999.0</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=PzLf1OJ1sm7dDb7Jbjeh9w%3D%3D.ZFaA7ikVNC%2BI%2FPVuD6CjCdotN09H5Vl4LIX2KUfcGbP0XKHzzil15gEgb3PrF0U%2FMN0E8uzn5bFqUFsRe1wRgGxfatH5eTGHM8ajIzG7aw0%3D" rel="nofollow">php里简单的对称加密算法</a></h3>
<pre><code class="php">
$content = "大家好,我是中国人,你是谁";
/**
* 简单对称加密算法之加密
* @param String $string 需要加密的字串
* @param String $skey 加密EKY
* @return String
*/
function encode($string = '', $skey = 'wenzi') {
$strArr = str_split(base64_encode($string));
$strCount = count($strArr);
foreach (str_split($skey) as $key => $value)
$key < $strCount && $strArr[$key].=$value;
return str_replace(array('=', '+', '/'), array('O0O0O', 'o000o', 'oo00o'), join('', $strArr));
}
/**
* 简单对称加密算法之解密
* @param String $string 需要解密的字串
* @param String $skey 解密KEY
* @return String
*/
function decode($string = '', $skey = 'wenzi') {
$strArr = str_split(str_replace(array('O0O0O', 'o000o', 'oo00o'), array('=', '+', '/'), $string), 2);
$strCount = count($strArr);
foreach (str_split($skey) as $key => $value)
$key <= $strCount && $strArr[$key][1] === $value && $strArr[$key] = $strArr[$key][0];
return base64_decode(join('', $strArr));
}
echo '<pre>';
echo "string : " . $content . " <br />";
echo "encode : " . ($enstring = encode($content)) . '<br />';
echo "decode : " . decode($enstring);</code></pre>
<h3><a href="https://segmentfault.com/q/1010000007021451">使用 MPDF 将HTML转为PDF</a></h3>
<pre><code class="php">$html = "对盲人初学者来说,它无需任何额外的修改。";
// $html = "These are the most used acronyms throughout this manual.";
include './mpdf/mpdf.php';
$mpdf=new mPDF('utf-8'); //这里改成UTF-8 即可
$mpdf->autoScriptToLang = true;
$mpdf->autoLangToFont = true;
$mpdf->WriteHTML($html);
$mpdf->Output();</code></pre>
<h3>strtr vs str_replace</h3>
<pre><code class="php">$arr = array('中国', '中国人'); //关键字
foreach($arr as $v) { $new[$v] = '<b>'.$v.'</b>'; }
var_export($new); //输出: array( '中国' => '<b>中国</b>', '中国人' => '<b>中国人</b>' )
$str = '我是中国人我爱中国';
echo strtr($str, $new)."\n"; //输出: 我是<b>中国人</b>我爱<b>中国</b>
//对比:str_replace会发生重复替换,下面代码会输出: 我是<b><b>中国</b>人</b>我爱<b>中国</b>
echo str_replace(array('中国人','中国'), array('<b>中国人</b>','<b>中国</b>'), '我是中国人我爱中国');</code></pre>
<h3>判断文件类型</h3>
<pre><code class="php">$image=file_get_contents($url);
file_put_contents($imagePath, $image); //将图片流存入服务器图片目录
$type=image_type_to_extension(exif_imagetype($imagePath)); //文件类型
$image = file_get_contents($url);
echo check_image_type($image);
function check_image_type($image)
{
$bits = array(
'JPEG' => "\xFF\xD8\xFF",
'GIF' => "GIF",
'PNG' => "\x89\x50\x4e\x47\x0d\x0a\x1a\x0a",
'BMP' => 'BM',
);
foreach ($bits as $type => $bit) {
if (substr($image, 0, strlen($bit)) === $bit) {
return $type;
}
}
return 'UNKNOWN IMAGE TYPE';
}
$finfo = new finfo(FILEINFO_MIME_TYPE);
var_dump($finfo->file('t.jpg')); // ==> image/jpeg</code></pre>
<h3>php Unicode正则</h3>
<pre><code class="php">$str=json_decode('"ux这\u202eわかぃまぃだDD"');
var_dump($str);//string(28) "ux这わかぃまぃだDD"
var_dump(preg_match('/^[\w\x{4e00}-\x{9aff}]{4,12}$/u', $str,$match));//int(0)
var_dump($match);</code></pre>
<h3>数组order by</h3>
<pre><code class="php">$arr = array(
'中国' => array(
'金牌' => 8,
'银牌' => 3,
'铜牌' => 6,
),
'俄罗斯' => array(
'金牌' => 3,
'银牌' => 6,
'铜牌' => 3,
),
'美国' => array(
'金牌' => 6,
'银牌' => 8,
'铜牌' => 8,
),
'澳大利亚' => array(
'金牌' => 4,
'银牌' => 0,
'铜牌' => 4,
),
'意大利' => array(
'金牌' => 3,
'银牌' => 4,
'铜牌' => 2,
),
);
// 实现 ORDER BY
foreach($arr as $k => $v) {
$sort['金牌'][$k] = $v['金牌'];
$sort['银牌'][$k] = $v['银牌'];
$sort['铜牌'][$k] = $v['铜牌'];
}
array_multisort(
$sort['金牌'], SORT_DESC,
$sort['银牌'], SORT_DESC,
$sort['铜牌'], SORT_DESC,
$arr);
var_export($arr);
arr = [
{'name':'国家一','score':[10,7,5]},
{'name':'国家二','score':[10,9,5]},
{'name':'国家三','score':[11,7,5]},
{'name':'国家四','score':[10,7,9]},
]
print sorted(arr, key=lambda a: '%03d%03d%03d' % tuple(a['score']), reverse=True)</code></pre>
<h3>base64图片处理</h3>
<pre><code class="php">/**
* 保存64位编码图片
*/
function saveBase64Image($base64_image_content){
if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){
//图片后缀
$type = $result[2];
//保存位置--图片名
$image_name=date('His').str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT).".".$type;
$image_url = '/uploads/image/'.date('Ymd').'/'.$image_name;
if(!is_dir(dirname('.'.$image_url))){
mkdir(dirname('.'.$image_url));
chmod(dirname('.'.$image_url), 0777);
umask($oldumask);
}
//解码
$decode=base64_decode(str_replace($result[1], '', $base64_image_content));
if (file_put_contents('.'.$image_url, $decode)){
$data['code']=0;
$data['imageName']=$image_name;
$data['url']=$image_url;
$data['msg']='保存成功!';
}else{
$data['code']=1;
$data['imgageName']='';
$data['url']='';
$data['msg']='图片保存失败!';
}
}else{
$data['code']=1;
$data['imgageName']='';
$data['url']='';
$data['msg']='base64图片格式有误!';
}
return $data;
}</code></pre>
<h3>php strtotime 获取上周一的时间</h3>
<pre><code class="php">>>> date('Y-m-d H:i:s',strtotime('-2 monday'))
=> "2016-10-03 00:00:00"
$days = date('w')==0?13:date('w')+6;
echo date('Y-m-d',time()-$days*86400);
date('Y-m-d', strtotime('-' . (6+date('w')) . ' days'));</code></pre>
<h3><a href="https://segmentfault.com/q/1010000007144881">合并数组</a></h3>
<pre><code class="php">$arr = array(
'0' => array(
'id' => 1,
'count' =>1,
),
'1' => array(
'id' => 2,
'count' =>1,
),
'2' => array(
'id' => 4,
'count' =>1,
),
'3' => array(
'id' => 2,
'count' =>1,
),
);
$new = $news = $newss = array();
foreach ($arr as $key => $value) {
if(!in_array($value['id'], $new)) {
$new[] = $value['id']; //$new保存不重复的id值
$news[$key] = $value; //$news保存不重复id的数组值
$newss[$value['id']] = $key; //$newss保存不重复的id的键值
}else {
$k = $newss[$value['id']]; //取出重复的id保存的第一个键值
$count = (int)$news[$k]['count']; //取出第一个相同id保存的count值
$news[$k]['count'] = $count+1; //赋值到新的数组
}
}
var_dump($news);</code></pre>
<p><a href="https://link.segmentfault.com/?enc=OPAL3GBQXhXOuWYQPARYIg%3D%3D.TAlk7KYNlOubeXu08adlUJpK1s15rvnL6hw4H9gIe2c%3D" rel="nofollow">https://github.com/iScript/YCms</a><br><a href="https://link.segmentfault.com/?enc=ZOMotYz7s5aHax0y8PcRMw%3D%3D.rvLaiiMHjLmiN3zytgIfdAQdiuGUCBbChTUzPTOlAhI%3D" rel="nofollow">https://phphub.org/topics/1759</a><br><a href="https://link.segmentfault.com/?enc=6xiwTCT%2B8nWiL%2BPUQEVS5Q%3D%3D.z11pC55xTWGq%2FV5R1b7BhpPLK2mEdc0qfEvWvqf4ohNSv36azI%2BJm4S2pJzXKn%2BjRJeDlecIkhvXGkLF5%2F%2BW%2BA%3D%3D" rel="nofollow">http://blog.csdn.net/phpfengh...</a><br><a href="https://link.segmentfault.com/?enc=%2BwvS5L2NGql%2BPH2gmgg7qA%3D%3D.E9AvQpd1XS4IZn1D6tMEaWmOVm3wBOe3DUSD6dIoW2e9AWUE%2FumlZ3TDbrF%2F1ond" rel="nofollow">https://phphub.org/topics/252...</a><br><a href="https://link.segmentfault.com/?enc=uxxrsjXNu4X8siTj9mpQag%3D%3D.Rwr2Ied0cELF1ViX6tQ3K7GCNhXI2NDN9kWxbdjel%2BzQceluElws%2FdQWlYhHBATBCZd%2B3nGVPebQslA3qF1gH5hlFvXNFvtcGdLVFrpGdZQ%3D" rel="nofollow">http://www.xiabingbao.com/enc...</a></p>
mysql记录
https://segmentfault.com/a/1190000006666297
2016-08-20T19:03:51+08:00
2016-08-20T19:03:51+08:00
苏生不惑
https://segmentfault.com/u/sushengbuhuo
2
<p>1、查找表中多余的重复记录,重复记录是根据单个字段(peopleId)来判断</p>
<pre><code class="php">select * from people
where peopleId in (select peopleId from people group by peopleId having count(peopleId) > 1)</code></pre>
<p>2、删除表中多余的重复记录,重复记录是根据单个字段(peopleId)来判断,只留有一个记录</p>
<pre><code class="php">delete from people
where peopleId in (select peopleId from people group by peopleId having count(peopleId) > 1)
and min(id) not in (select id from people group by peopleId having count(peopleId )>1)</code></pre>
<p>3、查找表中多余的重复记录(多个字段)</p>
<pre><code class="php">select * from vitae a
where (a.peopleId,a.seq) in (select peopleId,seq from vitae group by peopleId,seq having count(*) > 1)</code></pre>
<p>4、删除表中多余的重复记录(多个字段),只留有rowid最小的记录</p>
<pre><code class="php">delete from vitae a
where (a.peopleId,a.seq) in (select peopleId,seq from vitae group by peopleId,seq having count(*) > 1)
and rowid not in (select min(rowid) from vitae group by peopleId,seq having count(*)>1)</code></pre>
<p>5、查找表中多余的重复记录(多个字段),不包含rowid最小的记录</p>
<pre><code class="php">select * from vitae a
where (a.peopleId,a.seq) in (select peopleId,seq from vitae group by peopleId,seq having count(*) > 1)
and rowid not in (select min(rowid) from vitae group by peopleId,seq having count(*)>1)
</code></pre>
<p>6.mysql delete删除关联多表数据</p>
<pre><code class="php">DELETE reviews,reviews_description FROM reviews LEFT JOIN reviews_description ON reviews.reviews_id=reviews_description.reviews_id WHERE reviews.status='0'</code></pre>
<p>7.mysql delete in操作</p>
<pre><code class="php">delete from sns_hits where id not in (select id from another_table)
delete from sns_hits where id not in (select id from sns_hits)# error
CREATE TEMPORARY TABLE tmp_sns_hits ( `id` BIGINT(20) )
DELETE FROM t_tag
WHERE id NOT IN (SELECT * FROM (SELECT MAX(t .id) AS id FROM t_tag t GROUP BY tagname)t)
</code></pre>
<p>8.<a href="https://segmentfault.com/q/1010000006852224">一对多查询</a></p>
<pre><code class="js">select ID from 表2 where (select CONCAT(',', ksort , ',')AS ksort from 表1 ) LIKE CONCAT('%,', ID , ',%');
from [Mysql删除重复记录](http://blog.baitongda.cn/article/119)</code></pre>
<p>9.group by先排序后分组,group by默认的是第一条记录,相同的iID的记录不会先进行排序再group by <br>select <em> from (select </em> from t where 你的查询条件 order by 你的排序字段) group by 你的分组字段<br>10.<a href="https://link.segmentfault.com/?enc=keKYwppREhKwazmu%2FmYKkA%3D%3D.LOMzG3Kwux7tG5tF2HVzpMD2ArjHH8wPrd5CodYSKnr5QYhIsMJpkKbAGGag0%2BqJ422caMp4ATTqkS5dyONLym4rmaMSCbwjhKdHVjUHtPc%3D" rel="nofollow">mysql case when</a></p>
<pre><code class="js">SELECT count(enq_id) AS total, sum(purchase_amount) AS purchase
FROM temp_stock
WHERE purchase_date <> '0000-00-00'
AND purchase_date < '2012-08-01'
AND ( STATUS = 'Sold'
OR STATUS = 'In Stock'
OR STATUS = 'Ref')
AND CASE STATUS
WHEN 'Sold'
THEN delivery_date >= '2012-08-01'
ELSE 1=1
END
SELECT *
FROM logs
WHERE pw='correct'
AND CASE
WHEN id<800 THEN success=1
ELSE 1=1
END
AND YEAR(TIMESTAMP)=2011
WHERE
pw='correct'
AND (id>=800 OR success=1)
AND YEAR(timestamp)=2011
WHERE
pw='correct'
AND CASE WHEN id<800 THEN success=1 ELSE TRUE END
AND YEAR(timestamp)=2011 </code></pre>
<p><a href="https://link.segmentfault.com/?enc=R2IMtP3K%2FzZmHqI9EoZ2eg%3D%3D.J2a3YQsrZf9ZZCkVO1KPOM3tr00oms8pvzfYjyd3mnbxnE3WTcm2kpVEWzR4aIDTG4Xc8OxE4yWWB03AYF3RUQ%3D%3D" rel="nofollow">mysql where case when</a></p>
<pre><code class="php">--简单Case函数
CASE sex
WHEN '1' THEN '男'
WHEN '2' THEN '女'
ELSE '其他' END
--Case搜索函数
CASE WHEN sex = '1' THEN '男'
WHEN sex = '2' THEN '女'
ELSE '其他' END</code></pre>
<p>mysql 排序去重 sql 写法</p>
<pre><code class="php">| data_id | user_id | data_name |hits
| 1 | 2 | test1 | 140
| 2 | 2 | test2 | 200
| 3 | 3 | test2 | 110
| 4 | 3 | test2 | 10
| 5 | 1 | test2 | 130
| 6 | 4 | test2 | 10
| 7 | 4 | test2 | 100
查询出来下面的 3 条结果,也就是前 3 条点击量最多的数据, user_id 不能重复
SELECT
t.*
FROM
(
SELECT
user_id,
max(hits) AS max_hits
FROM
t
GROUP BY
user_id
) t2
LEFT JOIN t ON t.user_id = t2.user_id
AND t.hits = t2.max_hits
ORDER BY
t2.max_hits DESC
LIMIT 3
| data_id | user_id | data_name |hits
| 2 | 2 | test2 | 200
| 5 | 1 | test2 | 130
| 3 | 3 | test2 | 110 </code></pre>
<p><a href="https://link.segmentfault.com/?enc=pzCOTm%2BZS94DQ1a8xp%2BxKA%3D%3D.duPxEOrUAhlMqH0KxKw1qv6FWT3WIDdBXZnKZ%2Fk5vkRXgiXctCzsBeHMWIPPA%2B0R" rel="nofollow">order by 出现数据错误问题</a></p>
<pre><code class="js">select `stock`.*, `stock1`.`price_current` as `price_current1`, `stock1`.`rank` as `rank1`, `stock`.`price_current` - `stock1`.`price_current` as `percent1` from `stock` inner join `stock` as `stock1` on `stock`.`code` = `stock1`.`code` and `stock`.`date` = '2016-10-10' and `stock1`.`date` = '2016-09-30' and `stock`.`code` = '600817' order by `percent1` desc\G
price_current 这个字段设置了 UNSIGNED ,用 order by 会生成临时表,而临时表也就会同样是 UNSIGNED ,这就导致所有percent1为负值的都变成 0.00 了</code></pre>
<p><a href="https://link.segmentfault.com/?enc=jNpMtECAn%2BN54QIzGWESEg%3D%3D.UI6fNC%2BkJUlB4KEyqPe6Ia0NOpedG6qYGv5TroUs8oJS1MurSbM37aKlR1WkhgtI" rel="nofollow">MYsql 去重复语句</a></p>
<pre><code class="js">delete from `xxx` where id in (select * from (SELECT min(id) FROM `xxx` group by mail having count(mail)>1) as a);
create table tmp_xxx select min(id) as id,mail,password from xxx group by mail,password;
只保留一条不重复数据
DELETE T FROM MYTABLE T LEFT JOIN (SELECT MAX(A.ID) AS ID FROM MYTABLE A GROUP BY A.MAIL) TT ON T.ID = TT.ID WHERE TT.ID IS NULL
删除重复数据中的一条
DELETE T FROM MYTABLE T LEFT JOIN (SELECT MIN(A.ID) AS ID FROM MYTABLE A GROUP BY A.MAIL HAVING COUNT(A.MAIL) > 1) TT ON T.ID = TT.ID WHERE TT.ID IS NOT NULL
MySQL 唯一索引和插入重复自动更新
INSERT INTO table (id, user_id, token) VALUES (NULL, '2479031', '232') ON DUPLICATE KEY UPDATE user_id = VALUES(user_id), token = VALUES(token), online = VALUES(online)
user_id 是唯一索引字段,如果 insert 的时候该 user_id 已经存在,那么就将触发更新而不是插入,此时相当于执行了
update table set user_id = 2479031 token = 232 where user_id = 2479031
mysql导入大批量数据出现MySQL server has gone away的解决方法
http://blog.csdn.net/fdipzone/article/details/51974165
source /tmp/user.sql
mysql> show global variables like 'max_allowed_packet';
+--------------------+---------+
| Variable_name | Value |
+--------------------+---------+
| max_allowed_packet | 4194304 |
+--------------------+---------+
mysql> set global max_allowed_packet=268435456;
使用set global命令修改 max_allowed_packet 的值,重启mysql后会失效,还原为默认值。
如果想重启后不还原,可以打开 my.cnf 文件,添加 max_allowed_packet = 256M 即可
查看当前使用的配置文件my.cnf的方法
locate my.cnf
mysql启动时加载这个配置文件
ps aux|grep mysql|grep 'my.cnf'
如果没有设置使用指定目录的my.cnf,mysql启动时会读取安装目录根目录及默认目录下的my.cnf文件。
mysql --help|grep 'my.cnf'
在mysql默认读取的目录中,创建一个my.cnf文件(例如:/etc/my.cnf),把需要修改的配置内容写入,重启mysql后即可生效
You can't specify target table for update in FROM clause错误的解决方法 不能在同一个sql语句中,先select同一个表的某些值,然后再update这个表
mysql> update message set content='Hello World' where id in(select min(id) from message group by uid);
解决方法:select的结果再通过一个中间表select多一次,就可以避免这个错误
update message set content='Hello World' where id in( select min_id from ( select min(id) as min_id from message group by uid) as a );
Mysql select 中嵌套带子句https://www.v2ex.com/t/318573
SELECT
tt.*,u.name,(SELECT group_concat(title) FROM tag WHERE id IN (tt.tag)) as tag
FROM content tt
LEFT JOIN user u ON tt.owner=u.id
ORDER BY ts_created DESC
SELECT
tt.*,u.name,(SELECT group_concat(title) FROM tag WHERE FIND_IN_SET(id,tt.tag)) as tag
FROM content tt
LEFT JOIN user u ON tt.owner=u.id
ORDER BY ts_created DESC
分组
select p.id,p.productname,p.productcode,p.price,l.num from p
left join (select pid, sum(num) as num from wlms_stock group by pid) l on p.id = l.pid 从表2中获得每个pid的总数sum(num),然后用pid跟表1去连接,这样就既能获得表1的所有数据也能获得表2中的总数了https://segmentfault.com/q/1010000005941808
获取 用户最近10条文章 和 回复的文章https://segmentfault.com/q/1010000007169518
(SELECT id,title,create_time,'article' as type FROM fb_articles WHERE user_id = 4)
UNION
(SELECT a.id,a.title,b.create_time,'reply' as type FROM fb_articles as a,fb_replys as b WHERE a.id = b.article_id AND b.user_id = 4)
ORDER BY
create_time
DESC
LIMIT 10
SELECT * FROM(SELECT user_id,title,create_time FROM article UNION ALL SELECT user_id,article_id,create_time FROM reply) ar WHERE ar.user_id=xxx ORDER BY create_time desc LIMIT 10
MySQL 中将 varchar 字段转换成数字进行排序
将 attr_price 转换为数字再进行排序, *1 即可
'ORDER BY a.sort_order, g.attr_price * 1, g.goods_attr_id';
order by cast(col as unsigned)这会把小数位去掉,不合理
查询并更新到另个表的字段update 表 a inner join
表1 b set a.Nums = b.rcmd_count
where a.id = b.id</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=u4NW1yVSoupRyQ8HuAEJFA%3D%3D.V686dNqN%2BK3ncvIrs7Tyfjd6kcDRWCCMmeeJBO8ZG8uWdaNLJCEo6sKsN3%2FlH2bm" rel="nofollow">数据库返回的整型数据被偷换成了字符串类型</a></h3>
<p>问题出在了 PHP 的 MySQL 驱动上 <a href="https://link.segmentfault.com/?enc=g3POT44EkBl2XxxsJcfrRg%3D%3D.OvixQW8%2FNVfKVuRW189sV0wv6V%2Bke0vYX9BSdTmDkUYv21DcPjZaZ%2BXSIWI%2BDA%2BHLotjOm0ga1GbCzXYwo0%2Bl%2BjgpoEhsHZVKgK0jxlE23%2Fy5OVevj396Htx7IBoMZjw" rel="nofollow">http://stackoverflow.com/ques...</a> <br><a href="https://link.segmentfault.com/?enc=ZWTLOyMA3LXioqkJTLPa3A%3D%3D.cbkXbK13vHft%2FHNbowGeeSbkwvmknE3jvjaHOK0c8sR5aiTV5HM8O2RE%2FRkft9xOa9iVTFGgm1c%2BY6wNzFeuVFhJ8xSip5j3IzYKTtNpowATOYvQDgiRk%2Foft47s2mqoMJc%2BWE%2B6NoDaQUJvqAD3Qg%3D%3D" rel="nofollow">http://stackoverflow.com/ques...</a> <br>更新 PHP 的 MySQL 驱动 <br>sudo apt-get update<br>sudo apt-get install php5-mysqlnd</p>
<h3><a href="https://link.segmentfault.com/?enc=Qnr%2BW4jkpzrNeSqKSNNblQ%3D%3D.eRwYS9QbFkPvijPutvBoUhEyXDBVclAAHfKBvb5402Il1BGFDfwJFgwFjGyVJrM5TGSILOQgqN%2F77YI7P0%2BgbA%3D%3D" rel="nofollow">MySQL 慢查询定位</a></h3>
<pre><code class="js">编辑 my.cnf, 注意,需置于 mysqld 的 section 下
log_slow_queries = /tmp/mysql-slow.log
long_query_time = 2
重启 mysql.
只有 insert, update, delete 慢
set profiling=1;
SHOW PROFILES;
show profile for query 1;</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=5pgAUjmwmNvcgEjHyDNOeA%3D%3D.txhnF5HGtoO3JsSJdOpA%2Fne%2BHqvhr5II%2BbibJtpomEvpv11E6LJlrUn9ZNiLJC742bgb5lBVyFyBJaruK5RnGA%3D%3D" rel="nofollow">使用 Redis GeoHash 实现附近的XXX</a></h3>
<pre><code class="js">这里 sicily 类似山东省,而 Palermo, Catania 类似烟台、威海,即 Palermo、Catania 是 sicily 辖区内的城市。
redis> GEOADD Sicily 13.361389 38.115556 "Palermo" 15.087269 37.502669 "Catania"
(integer) 2
redis> GEODIST Sicily Palermo Catania
"166274.15156960039"
redis> GEORADIUS Sicily 15 37 100 km
1) "Catania"
redis> GEORADIUS Sicily 15 37 200 km
1) "Palermo"
添加时,经度在前,维度在后。
GEORADIUSBYMEMBER yeda "富士康" 1 km
小心,前方有坑! 返回的结果默认是无序的,即不会按照距离远近进行排序。需要手动加上 ASC, DESC 进行排序。
GEORADIUSBYMEMBER yeda "富士康" 10 km WITHDIST ASC
如何在 Laravel 中使用
composer require predis/predis
$items = Redis::georadius("yeda", $lng, $lat, 20, "km", "WITHDIST", "ASC");
2) "Catania"</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=HYjcBS1y79OIF17GEHgCCw%3D%3D.9n3mbAeX1YTNeWryAP7IgHcLYYcItO6J7wyVTx%2FoQiX%2FL9DW0F4sPhmHcbTYpSqq8nUzu94ZPOGKc2L8xw9nnA%3D%3D" rel="nofollow">MySQL 崩溃导致 Discuz! Database Error (2002) notconnect 错误</a></h3>
<p>innodb_buffer_pool_size 的默认值,在 5.5 之后就被调成了 128M, 参考最新的 mysql 5.5, 5.6 文档<br>在 my.conf 中将这个 buffer 调小</p>
<p>innodb_buffer_pool_size=32M</p>
<h3><a href="https://link.segmentfault.com/?enc=o%2BivzAf15FTcmeepZt1MLQ%3D%3D.bPhs4T9gw00ZbgVGfV2PnNkikL6x1lKFAlOO0XIGuFw%3D" rel="nofollow">Redis监控方法</a></h3>
<p>redis-cli info<br>获取Redis所有Key的方法:</p>
<p>1.终端</p>
<p>获取所有Key命令:redis-cli keys ‘*’ ;</p>
<p>获取指定前缀的key:redis-cli KEYS “edu:*”</p>
<p>如果需要导出,可以redis-cli keys ‘*’ > /data/redis_key.txt</p>
<p>删除指定前缀的Key redis-cli KEYS “edu:*” | xargs redis-cli DEL</p>
<p>2.PHP获取Redis所有Key</p>
<p>获取Redis所有Key:$keys = $redis->keys(‘*’);</p>
<p>获取指定前缀的Key:$keys = $redis->keys(‘edu*’);</p>
<p>删除指定前缀的Key :$redis->delete($redis->keys(‘image*’));</p>
<h3><a href="https://link.segmentfault.com/?enc=lpPX3dc%2FPmrMp5Aeb%2F81MA%3D%3D.DHmn5MTsAHTkctfeZaUi5cvCCGz2KXpTLVtPXEcmaN0hKenBNDxAb0864WSN0f6Z4nLwrNzhOWlJM7OvWG9SJw%3D%3D" rel="nofollow">mysql递归查询</a></h3>
<pre><code class="js">https://segmentfault.com/q/1010000007523914
select id,name,pid from (select *from user order by pid,id) a,(select @pv := '8') init where (find_in_set(pid,@pv)>0) and @pv := concat(@pv,',',id) or id = 8;
mysql> delimiter //
mysql>
mysql> CREATE FUNCTION `getChildLst`(rootId INT)
-> RETURNS varchar(1000)
-> BEGIN
-> DECLARE sTemp VARCHAR(1000);
-> DECLARE sTempChd VARCHAR(1000);
->
-> SET sTemp = '$';
-> SET sTempChd =cast(rootId as CHAR);
->
-> WHILE sTempChd is not null DO
-> SET sTemp = concat(sTemp,',',sTempChd);
-> SELECT group_concat(id) INTO sTempChd FROM treeNodes where FIND_IN_SET(pid,sTempChd)>0;
-> END WHILE;
-> RETURN sTemp;
-> END
-> //
Query OK, 0 rows affected (0.00 sec)
mysql> delimiter ;
mysql> select * from treeNodes
-> where FIND_IN_SET(id, getChildLst(1));
+----+----------+------+
| id | nodename | pid |
+----+----------+------+
| 1 | A | 0 |
| 2 | B | 1 |
| 3 | C | 1 |
| 4 | D | 2 |
| 5 | E | 2 |
| 6 | F | 3 |
| 7 | G | 6 |
+----+----------+------+
7 rows in set (0.01 sec)</code></pre>
<h3>mysql分组</h3>
<pre><code class="js">$res = ['2016-11-18','2016-11-19'];
$s=implode("','",$res);//"2016-11-18','2016-11-19"
echo '\''.$s.'\'';//"'2016-11-18','2016-11-19'"
$sql="select date_format(created,'%Y-%m-%d') as date,count(*) from test where date_format(created,'%Y-%m-%d') in ('\'.$s.'\') group by date order by id desc limit 5;"</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=5LW%2Fb2H2Z9lguMjbSPsOpg%3D%3D.2FzMdYeXuw25%2BkyI8GmSLsSPA8PjrNC0zGbN6I2DTexhZrifRhdCFQSkD7CYFByF" rel="nofollow">mysql优化查询速度</a></h3>
<p>select id from t where num=10 or num=20</p>
<p>select id from t where num=10<br>union all<br>select id from t where num=20<br>select num from a where num in(select num from b)<br>select num from a where exists(select 1 from b where num=a.num)</p>
<h3><a href="https://link.segmentfault.com/?enc=eOGfdB1gLBvm9ZUggL6oSQ%3D%3D.KePqdBwNWDBZost8j8pPpK8s7mBpj%2BDK7a%2FbeyysEZPsDyzxLPiQ%2Fni23wdon6BD" rel="nofollow">MySQL日志查询分析工具pt-query-digest</a></h3>
<p>直接分析慢查询文件<br>pt-query-digest slow.log > slow_report.log<br>分析最近12小时内的查询<br> pt-query-digest --since=12h slow.log > slow_report2.log</p>
<h3>批量更新</h3>
<pre><code>update table_name set field_name = CASE id
WHEN id1 THEN field_value,
WHEN id1 THEN field_value
END</code></pre>
<h3>一个 MySQL 用户名长度的坑</h3>
<p>MySQL user names can be up to 32 characters long (16 characters before MySQL 5.7.8). <a href="https://link.segmentfault.com/?enc=q%2FQajGerftU%2BoL8MX6DIbw%3D%3D.uQaelPj31fv735BO%2FTsHnS3GPdkBMtG7cNa6rS2DiJHjoeiVUo8QTmLmAZgS6Wl4PFmlGIbws6GLz1McjZpbKA%3D%3D" rel="nofollow">http://dev.mysql.com/doc/refm...</a><br>grant all privileges on <em>.</em> to joe@10.163.225.87 identified by ‘123′;</p>
<h3><a>Mysql FIND_IN_SET 语句原始排序 </a></h3>
<p>find_in_set单条记录没问题,比如唯一id的in。多条记录order会失效select * from act_log where answer in ('B','C','CD') order by find_in_set( answer,"'B','C','CD'")<br>排序错误:CD,C,BB,C<br>select * from tb1 order by a desc ,id desc limit 3; 用limit和order by 一个非唯一字段时,结果集并不总是确定的.已经确定为bug<a href="https://link.segmentfault.com/?enc=q3ja9JFAxZGJXA7RQ0zBEQ%3D%3D.8Iq5IiTtmqtz13YCI9nOlgZcZOeQze8W3GM4%2FfiSwSrxzH6s%2FHAHT%2FS9tSrL9fS7" rel="nofollow">http://www.codesec.net/view/2...</a><br>select SUM(<code>fee</code>) AS <code>income</code>, SUM(IF(<code>type</code>=5, <code>fee</code>, 0)) AS <code>reward</code></p>
<h3><a href="https://link.segmentfault.com/?enc=7xL6v8vsJfPqeElMFGW%2FJg%3D%3D.xy1oaak97mdhbDsKC8%2B6mN1zb%2FN0ly329bcnL1paMxrHtUE%2FRAb9qnjFZ6TFa7U8EmFF132a353i5LSEjGkCBg%3D%3D" rel="nofollow">mysql 如何实现先排序后分组</a></h3>
<p>1、可以先把数据按照你的条件要求,使用order by排好序<br>2、在查询sql外面,再包一层查询,使用group by<br>例如: select <em> from (select </em> from t where 你的查询条件 order by 你的排序字段) group by 你的分组字段</p>
<h3><a href="https://link.segmentfault.com/?enc=CpzAZ7IdDyZXfosUe0As9w%3D%3D.xGqMkszElmix6xLpX8ELugrK8mTTbfsbjyL9W0SJCf6nfYNdwEarUag%2BPv2yfMPE" rel="nofollow">MySQL中varchar最大长度是多少</a></h3>
<p>(1)单个字段如果大于65535,则转换为TEXT 。</p>
<p>(2)单行最大限制为65535,这里不包括TEXT、BLOB</p>
<h3>查询一个月当中每个人每天的第一次和最后一次记录</h3>
<p>SELECT MIN(card_time) AS mintime, MAX(card_time) AS maxtime , user_sn, card_date FROM testtbl GROUP BY user_sn, card_date</p>
<h3>数据库去除重复记录</h3>
<p>insert into xxxx (select xxx from xxxx) <br>然后再 delete from xxx where id in (select xxx from xxxx)</p>
<h3><a href="https://link.segmentfault.com/?enc=RoLB5e8%2FViUaCXG5OeACFA%3D%3D.c3m7BrC%2FNJubjh9MlXsyoI3WVTqdGkDR0unLqoW5dSD5c5czD8798bcdTcpqSUNKwn9RTUXTe1yNEoKZ0BiFgjalDELaBrUAcYSzUpqxRvI%3D" rel="nofollow">alter table 锁表</a></h3>
<p>新建表,数据复制到新表然后 rename 切换 <a href="https://link.segmentfault.com/?enc=S6rYM540nfh0HWU7ITvy0w%3D%3D.4JvYlKoMACVyuPHFBfUWApccJfB4tMP80zJt34Adig%2BjBQmHfp3Ce0J0M9clS1Cn4iNdlF8aYV6KDyg0OkycDA%3D%3D" rel="nofollow">http://www.cnblogs.com/wangta...</a></p>
<h3>按ID降序排序,如果用户状态为0(未激活),则注册时间升序,排在结果最后</h3>
<p>select *from user order by status desc,case status when 1 then id end desc,case status when 0 then created_at end asc;</p>
<h3>过滤 三个字段 有重复的记录</h3>
<p>select * FROM tt t1, tt t2 WHERE t1.userid = t2.userid and t1.pid = t2.pid and t1.tid = t2.tid and s1.id != s2.id</p>
<h3>查询total_time > 100</h3>
<p>SELECT *<br>FROM <code>tuanke_time</code> <br>LEFT JOIN tuanke_student ON tuanke_student.Sid = tuanke_time.studentID <br>GROUP BY tuanke_time.studentID having SUM(tuanke_time.time) > 100;</p>
<h3>查每个用户第一次记录</h3>
<p>select user,num from (select * from tb order by time asc) as a group by a.user;</p>
<h3>删除重复记录</h3>
<pre><code class="js">DELETE FROM price_monitor WHERE id NOT IN (
SELECT * FROM (
SELECT MAX(id) FROM price_monitor GROUP BY domain
)
as tmp
)</code></pre>
<h3>limit sum</h3>
<p>select uid, sum(skip) as sumskip, time from (select uid, skip, time from attendance where uid = 8499 order by time limit 3) as subt;</p>
<h3>mysql删除大量数据,直接delete会锁表</h3>
<pre><code class="js">DELIMITER $$
CREATE PROCEDURE delete_temp_tab()
BEGIN
REPEAT
DELETE FROM test.`tab` WHERE id > 111352 LIMIT 1000;
UNTIL ROW_COUNT()=0 END REPEAT;
END $$
DELIMITER ;
CALL delete_temp_tab();
DROP PROCEDURE IF EXISTS delete_temp_tab;</code></pre>
<h4>mysql 分页查询优化</h4>
<pre><code class="js">EXPLAIN
SELECT
`id`
FROM
`table`
WHERE `node` = 2
ORDER BY `create_at` DESC
LIMIT 12 OFFSET 69996
#查询1
SELECT
`id`
FROM
`table`
WHERE `node` = 2
ORDER BY `id` ASC
LIMIT 10
查询第二页的SQL如下
SELECT
`id`
FROM
`table`
WHERE `node` = 2 AND `id`>10
ORDER BY `id` ASC
LIMIT 10</code></pre>
<h3><a href="https://segmentfault.com/q/1010000007571749">每次取10000 三次取完</a></h3>
<pre><code class="js">分块
$sql = 'SELECT xxx FROM table WHERE xxx LIMIT limit :limit offset :offset';
$limit = 10000;
$offset = 0;
do{
$stmt = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$stmt->execute(array(':limit' => $limit, ':offset' => $offset));
$data = $stmt->fetchAll();
// 处理逻辑
$offset += $limit;
}while(count($data));
游标,按行读取返回
$sql = 'SELECT xxx FROM table WHERE xxx';
$stmt = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_LAST);
do {
// 处理逻辑 $row
} while ($row = $stmt->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_PRIOR));</code></pre>
<h3>正则匹配手机号前缀</h3>
<p>SELECT name FROM users WHERE phone REGEXP '^15[1-4]';</p>
<h3>redis setbit</h3>
<p>setbit key offset,其中offset用userid取代,如果ID为1的用户是男性就setbit key 1 1,<br>如果是女性就setbit key 1 0,获取ID为1的性别就getbit key 1</p>
<h3><a href="https://segmentfault.com/q/1010000007632815">数据迁移</a></h3>
<p>在没有索引的情况下,我会采用先delete后insert。<br>但在有索引的情况下,我会采用以下方式先update后insert</p>
<h3><a href="https://segmentfault.com/q/1010000007650333">每半个小时的数据</a></h3>
<pre><code class="js">delimiter $$
CREATE PROCEDURE test()
begin
declare begintime int(10);
set begintime = unix_timestamp("2016-7-31 23:59:59");
loop1:LOOP
IF begintime > unix_timestamp("2016-9-30 23:59:59") then
leave loop1;
END IF;
select * from tablename where timestamp between begintime and begintime+1800;
set begintime = begintime + 1800;
END LOOP loop1;
end;$$</code></pre>
<h3><a href="https://segmentfault.com/q/1010000007701597">子查询不支持limit</a></h3>
<pre><code class="js">SELECT * FROM yi_user_joke WHERE id in (SELECT id FROM yi_user_joke WHERE status='2' ORDER BY audit_time desc LIMIT 499950,10 ) ORDER BY audit_time desc LIMIT 10 ;
ERROR 1235 (42000): This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'
SELECT * FROM yi_user_joke a inner join (SELECT id FROM yi_user_joke WHERE status='2' ORDER BY audit_time desc LIMIT 499950,10 ) as b on a.id=b.id ORDER BY a.audit_time desc LIMIT 10 ;
SELECT * FROM yi_user_joke WHERE id in (select *from (SELECT id FROM yi_user_joke WHERE status='2' ORDER BY audit_time desc LIMIT 499950,10 ) as b) ORDER BY audit_time desc LIMIT 10 ;</code></pre>
<h3><a href="https://segmentfault.com/q/1010000007709997">分组取前五</a></h3>
<pre><code class="js">select * from table as a where (select count(distinct(total)) from table as b where a.stage_id = b.stage_id and b.total > a.total) < 5;where中的select是保证遍历所有记录,取每条记录与当前记录做比较,只有当table表中同一stage_id不超过5个人total当前选择item的total高时,这个item就算是每组total排行的前5名</code></pre>
<h3>查询每个部门工资前3名</h3>
<p><code>select * from table d1 where (select count(*) from table d2 where d2.bumen=d1.bumen and d2.salary>d1.salary) < 3 order by d1.salary desc</code></p>
<h3><a href="https://link.segmentfault.com/?enc=oc6oNFZa%2Brk5Xnl2oDjdyQ%3D%3D.8zsxynMf4o44pVgMMwq8QWxYQmUa6X3PHASPbiXA5Al9ExKmIM4dTrSx1iGeCaEEPO%2FymrW8277S1sKb8TeXa24UjmEvasULtXKiG3ssddc%3D" rel="nofollow">从一个表中选出最后几个元素</a></h3>
<pre><code class="js">SELECT * FROM (
SELECT * FROM tmp_table ORDER BY id DESC LIMIT 50
) sub
ORDER BY id ASC
选出分组求和的平均数SELECT AVG(sum_column1)
FROM (SELECT SUM(column1) AS sum_column1)
FROM t1 GROUP BY column1) AS t1;</code></pre>
<h3><a href="https://link.segmentfault.com/?enc=peLIWJK8cX69vCaJnV%2FZqQ%3D%3D.uhZu0pV0V4FZ5cTKWwenWFs8p%2FsfpqkKxb2dQypf4Js%3D" rel="nofollow">group by </a></h3>
<pre><code class="js">group by 是用于分组统计的,会按照分组字段进行排序,如果 order by 和 group by 同时出现,order by 是对 group by 的结果排序,因此取的是根据 group by 排序后各组第一条,但这是有逻辑错误的,好像只有在 MySQL 中可行。
这句 SQL 就好比一个班级的女生按照寝室分组,然后你想知道分组的结果属于谁? 其实谁都不属于,但你可以得到每个组中属性的最大值,最小值,或者具有分组统计意义的信息。 从 MySQL 5.7.5 起,SELECT 不在 GROUP BY 中的字段将会导致数据库拒绝执行查询
order by 只有后面跟着 limit 在子查询才有意义
select * from (select * from table order by <字段 2> limit 1000) as temp group by <字段 1> </code></pre>
开发拾遗
https://segmentfault.com/a/1190000005128780
2016-05-15T19:07:10+08:00
2016-05-15T19:07:10+08:00
苏生不惑
https://segmentfault.com/u/sushengbuhuo
2
<h3>python unicode字符串转成中文</h3>
<pre><code class="php">s = 'u6d4bu8bd5u957fu5ea6'
s = s.replace('u', '\u')
print s.decode('unicode-escape')</code></pre>
<h3>php 二进制直接量</h3>
<pre><code class="php">$bin = bindec('110011');
$bin = 0b110011;</code></pre>
<h3>php foreach list</h3>
<pre><code class="php">$arr = [
[1, 2],
[3, 4],
];
foreach ($arr as list($a, $b)) {
echo $a.$b\n";
}</code></pre>
<h3>PHP ==和隐式转换</h3>
<pre><code class="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</code></pre>
<h3>== 、switch、in_array 的松比较</h3>
<pre><code class="php">// 如果 $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</code></pre>
<h3>javascript Date对象的浏览器兼容性问题</h3>
<p>// chrome同时支持'-'和'/'分割日期的时间字符串;safari不支持'-'分割日期的时间字符串</p>
<pre><code class="php">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]);</code></pre>
<h3>javascript 模拟Object.keys()</h3>
<pre><code class="php">function keys(obj){
var a = [];
for(a[a.length] in obj);
return a;
}</code></pre>
<h3>javascript数组去重</h3>
<pre><code class="php">function dedupe(array){
return Array.from(new Set(array));
}
dedupe([1,1,2,3]) //[1,2,3]</code></pre>
<h3>工具</h3>
<p>// 命令行提示tldr npm install -g tldr</p>
<p><img src="/img/bVvGoP" alt="clipboard.png" title="clipboard.png"><br><a href="https://link.segmentfault.com/?enc=pPfOCvRzpJL6TNybMnBrKQ%3D%3D.CkN8kM89sXm5L3ioLr1DBkKWT3pc%2BC4M0RCrJRWicic%3D" rel="nofollow">octotree</a> 是一款可为 GitHub 和 GitLab 添加侧边栏文件导航的 Chrome 和 Opera 插件<br><a href="https://link.segmentfault.com/?enc=j5tfJkULXWf5hhB8m%2FZlsg%3D%3D.zq%2FhAN5Pmqa1vcumaOtauBy97H1tyUiynwJ4PmwxqOI%3D" rel="nofollow">python下载视频工具</a></p>
<h3>Sublime Text3 汉化</h3>
<p>// Package Control:Install Package,输入Chinese,选择ChineseLocalization</p>
<h3>javascript reduce</h3>
<pre><code class="php">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);</code></pre>
<h3>jquery插件</h3>
<p>输入提示自动完成插件<a href="https://link.segmentfault.com/?enc=IK17egoNVY46eNMDW%2Bjhiw%3D%3D.oFaej3zK3li%2FH0Ec1fJgF0P%2FhFLLoVLI6VBXT4BjCmCT8C3gLq6%2FIxceU6DPnzIV" rel="nofollow">tokeninput</a><br><a href="https://link.segmentfault.com/?enc=1OWuwBSKJCSuM4HEuElUnw%3D%3D.tTQ%2FhZm%2FeF68KSvCwY5gaJgHD2td4%2Bbhc8NuDp59Edk%3D" rel="nofollow">tablesorter</a> 表格排序<br><a href="https://link.segmentfault.com/?enc=bSlaU%2FYZsr7DcguIM5aVxw%3D%3D.bqlw9br8sw22xWLGFfGyYfBDvLG4m6XvokFMrLz9PjiPofNIrrtDSXRy5sHviYkd" rel="nofollow">Date.js</a>执行日期/时间的计算<br><a href="https://link.segmentfault.com/?enc=dBfTaPG4NbjqKcJ6z62ANg%3D%3D.Yd%2F%2BImvyMrt%2FZdQKOMsFm33rpCSQcZG7wLiI4CcCx%2BKHCM0i9Ldu0CA1G9wJJWav" rel="nofollow">图片裁剪</a><br><a href="https://link.segmentfault.com/?enc=AElacSS7apwSgMrO%2F3k%2FCQ%3D%3D.A8EKEQUan0efSc3YGs5oh0VDmPK9dbGR231VC3ipEK0%3D" rel="nofollow">日期选择插件pickadate.js</a><br><a href="https://link.segmentfault.com/?enc=6cS4NSac39mdjOlRdAM50g%3D%3D.lvD507b%2BWMNobxTrzVoCbI4In23%2F%2BWeVIPs1CgiyO9I%3D" rel="nofollow">javascript刻度条插件</a></p>
<h3>0.1+0.2</h3>
<pre><code class="php">Math.round( (.1+.2)*100)/100; //0.3</code></pre>
<h3>mysql分解联合查询</h3>
<pre><code class="php">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) </code></pre>
<h3>字符串中每个字母重复出现的次数</h3>
<pre><code class="php"> 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}</code></pre>
<h3>composer</h3>
<p><a href="https://link.segmentfault.com/?enc=pUdD1O5oEHeJme5HpK3b1Q%3D%3D.4LBt%2FC7KPwXot7SI1kIdBIW7yJX9jgyvgIgVmwclv3op0XMqs9COKOmrwyyrK%2Bet" rel="nofollow">PHP HTTP请求套件</a><br><a href="https://link.segmentfault.com/?enc=Q4BoHYHOhDpRo0EEbwsaXw%3D%3D.Mf1KL6FEUBQz9bF%2F80dTx9JxiawASznzbBByh9j5Hok%3D" rel="nofollow">实现 Laravel 模型的无限极分类</a></p>
<h3>php一维数组 转 多维数组</h3>
<pre><code class="php">$arr = ['a', 'b', 'c', 'd'];
$child = array();
$res = [];
while($v = array_pop($arr)) {
$res = [$v => $child];
$child = $res;
}</code></pre>
<h3>python中字符串的按位或</h3>
<pre><code class="php">a = "1000111000"
b = "1000000001"
c = int(a, 2) | int(b, 2)
print('{0:b}'.format(c))#1000111001</code></pre>
<h3>python生成斐波拉契数列</h3>
<pre><code class="php">def fib(max):
n, a, b = 0, 0, 1
while n < max:
print(b)
a, b = b, a + b
n = n + 1
return 'done'</code></pre>
<h3>php正则匹配</h3>
<pre><code class="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]</code></pre>
<h3>php max/min</h3>
<pre><code class="php">max(ceil(-0.5), 0) # -0.0
max(0, ceil(-0.5)) # 0</code></pre>
<h3>NaN</h3>
<pre><code class="php">_.isNaN = function(obj){
return _.isNumber(obj) && obj !==+obj;
};</code></pre>
<h3>Mysql 用 一张表中的数据更新另一张表的数据</h3>
<p><code>update tableA as ca inner join tableB as cb set ca.thumbs=cb.thumbs where cb.courseid=1;</code><br>24.php后期静态绑定</p>
<pre><code class="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</code></pre>
<h3>json_encode输出动态javascript</h3>
<pre><code class="php">$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"]</code></pre>
<h3>String.fromCharCode</h3>
<pre><code class="php">var regex_num_set = /&#(\d+);/g;
var str = "Here is some text: &#27599;&#26085;&#19968;&#33394;|&#34013;&#30333;~"
str2 = str.replace(regex_num_set, function(_, $1) {
return String.fromCharCode($1);
});//"Here is some text: 每日一色|蓝白~"</code></pre>
<h3>日期格式补0</h3>
<pre><code class="php">"2015-5-2".replace(/(?=\b\d\b)/g, '0')#"2015-05-02"
"2015-5-2".replace(/-(\d)(?=-|$)/g, '-0$1')#"2015-05-02"</code></pre>
<h3>array_merge如果传的参数中有一个不是数组;则返回null</h3>
<pre><code class="php">$arr = [1,2,3];
$new = '';
array_merge($arr, $new);//null
array_merge($arr, (array)$new);</code></pre>
<h3>php switch使用的是==比较;而不是===</h3>
<pre><code class="php">switch (0) {//switch (strval(0))
case 'test1':
echo 1;
case 'test2':
echo 2;
case 'test3':
echo 3;
break;
}</code></pre>
<h3>javascript数组的map方法对一个数组中的空位置(没有设置过值或值被删除)不会调用提供的callback回调函数</h3>
<pre><code class="php">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
});</code></pre>
<h3>setTimeout传入参数</h3>
<pre><code class="php">for(var i = 0; i<data.length; i++){
(function(i){
setTimeout(function (){
console.log(data[i])
},2000);
})(i)
}
//es6
for(let i = 0; i<data.length; i++){
setTimeout(function (){
console.log(data[i])
},2000);
}</code></pre>
<h3>循环中promise</h3>
<pre><code class="php">var userIds = ['aaa', 'bbb', 'ccc'];
//这里getUserById返回的是Promise
var promises = arr.map(userIds => getUserById(userId));
Promise
.all(promises)
.then(function(users) {
console.log(users); //这里就是users的列表了
});</code></pre>
<h3>hasClass</h3>
<pre><code class="php">function hasClass(element, cName) {
return (' ' + element.className + ' ').indexOf(' ' + cName + ' ') > -1;
}</code></pre>
<h3>补零</h3>
<pre><code class="php">"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;
});</code></pre>
<h3>getUrlParameter</h3>
<pre><code class="php">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];
}
}
};</code></pre>
<h3>随机数</h3>
<pre><code class="php">Math.round(Math.random() * 1000)//生成0~1000之间的随机整数
((Math.random() * 10 + 5).toFixed(1) - 0)//产生一个5到15之间,包含一位小数的随机数Math.floor((Math.random() * 10 + 5) * 10) / 10</code></pre>
<h3>显示隐藏元素</h3>
<pre><code class="php">window.onload=function(){
var li=document.getElementsByTagName("li");
for(var j=0;j<li.length;j++){
li[j].onclick=function (){
for(var i=0;i<li.length;i++){
li[i].className='';
}
this.className='a';
}
}
};</code></pre>
<h3>判断一个json对象中是否含有某个key</h3>
<pre><code class="php">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;
}</code></pre>
<h3>数组合并</h3>
<pre><code class="php">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);</code></pre>
<h3>区间索引</h3>
<pre><code class="php">function getRangeIndex(scrollTop) {
var i=0;
ranges = [2,3,6,22,88];
for (;i<ranges.length;i++)
if (scrollTop<ranges[i]) break;
return i-1;
}</code></pre>
<h3>快速生成一个数组,数组的元素是前N个自然数</h3>
<pre><code class="php">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(','))</code></pre>
<h3>每取10行放到一个新的文件中</h3>
<pre><code class="php">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)</code></pre>
<h3>按首字母排序</h3>
<pre><code class="php">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"]</code></pre>
<h3>删除字符串的空格</h3>
<pre><code class="php">$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</code></pre>
<h3>PHP解析JSON得到科学计数法后的int</h3>
<pre><code class="php">$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</code></pre>
<h3>MySQL中所有数据库的数据大小</h3>
<pre><code class="php">SELECT table_schema, (
(
SUM( DATA_LENGTH ) + SUM( INDEX_LENGTH )
) /1024 /1024
) AS datasize
FROM `TABLES`
GROUP BY table_schema
LIMIT 0 , 30
</code></pre>
<h3>合并数组</h3>
<pre><code class="php">//一般会用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]];</code></pre>
<h3>php上传文件</h3>
<pre><code class="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就会把它当成是文件上传处理
}</code></pre>
<h3>php stdclass</h3>
<pre><code class="php">$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);</code></pre>
<h3>PHP浮点数运算精度</h3>
<pre><code class="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</code></pre>
<h3>防止浏览器屏蔽window.open</h3>
<pre><code class="php"><button onclick=“test()”>点击</button>
<script>
function test(){
var frame=window.open(“about:blank”,“_blank”);
$.get(“/”,function(){
frame.location=“http://www.baidu.com”;
});
}
</script></code></pre>
<h3>修改session_id的保存位置</h3>
<pre><code class="php">session_set_cookie_params(0,‘/’,‘testdomain’);
session_start();//开启session
echo ‘Old Session id:’.session_id().‘<br>’;
session_regenerate_id(true);//重置session_id,并使原session无效
echo ‘New Session id:’.session_id().‘<br>’;
//echo session_id()失效
setcookie(session_name(),session_id(),0,‘/’,‘testdomain’);//手动更新session_id</code></pre>
<h3>CRUL命令简单分析请求细节所占用的时间</h3>
<pre><code class="php">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</code></pre>
<h3>php上周时间</h3>
<pre><code class="php">echo '<br>上周起始时间:<br>';
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'))</code></pre>
<h3>{ "a":"1","b":"2"} 变成 "a:1;b:2"</h3>
<pre><code class="php">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(';');</code></pre>
<h3>python格式化</h3>
<pre><code class="php">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')]
}</code></pre>
<h3>PHP生成连续数据</h3>
<pre><code class="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));</code></pre>
<h3>javascript对象复制</h3>
<pre><code class="php">function clone(e) {
var t = {};
for (var n in e) e.hasOwnProperty(n) && (t[n] = e[n]);
return t;
}</code></pre>
<h3>过滤掉emoji表情</h3>
<pre><code>function filterEmoji($str)
{
$str = preg_replace_callback(
'/./u',
function (array $match) {
return strlen($match[0]) >= 4 ? '' : $match[0];
},
$str);
return $str;
}</code></pre>
<h3>javascript选择器</h3>
<pre><code class="php">function $(selector, context) {
context = context || document;
var elements = context.querySelectorAll(selector);
return Array.prototype.slice.call(elements);
};</code></pre>
<h3>jquery对象对比,开发中要尽量先保存创建的jQuery对象,然后多次使用</h3>
<pre><code class="php">var elem1 = $("#navList li");
var elem2 = $("#navList li");
elem1 ==elem2;//false
//应该比较dom本身不是 jQuery对象
$('div') === $('div') //false
$('div')[0] === $('div')[0]//true</code></pre>
<h3>for 循环和异步调用的问题</h3>
<pre><code>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)
}</code></pre>
<h3>按照字母和数字的顺序进行排序</h3>
<pre><code class="php">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"]
});</code></pre>
<h3>JSON.parse转换报错</h3>
<pre><code class="php">var getValue = function (objStr) {
return new Function("return " + objStr)()
}
// 调用
var res1 = getValue('{"foo" : 1, }')//Object {foo: 1}
JSON.parse(res1);</code></pre>
<h3>javascript正则替换</h3>
<pre><code class="php">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</code></pre>
<h3>javascript闭包</h3>
<pre><code class="php">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();</code></pre>
<h3>javascript array reduce()</h3>
<pre><code class="php">arr.reduce(function (pre, cur, index) {
if (index >= 3) {
return pre;
}
return pre + cur;
}, initVal);
</code></pre>
<h3>javascript 汉字占2字节</h3>
<pre><code class="php">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('');
}</code></pre>
<h3>隐藏手机号</h3>
<pre><code class="php">echo substr_replace ('13412343312','****',3,4) ;//134**3312</code></pre>
<h3>javascript数组降维</h3>
<pre><code class="php">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);
});</code></pre>
<h3>获取content-type</h3>
<pre><code class="php">//获取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;
}</code></pre>
<h3>PHP随机合并数组并保持原排序</h3>
<pre><code class="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',
)</code></pre>
<h3>仿知乎复制文本自带版权声明</h3>
<pre><code class="php">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 = ''
+ '著作权归作者所有。<br>'
+ '商业转载请联系作者获得授权,非商业转载请注明出处。<br>'
+ '作者:DIYgod<br>'
+ '链接:' + window.location.href + '<br>'
+ '来源:Anotherhome<br><br>'
+ 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);
}
}</code></pre>
<h3>根据用户积分判断等级</h3>
<pre><code class="php">//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;
}</code></pre>
<h3>0000000序列递增</h3>
<pre><code class="php">for ($i = 0; $i < 100; $i++) {
$zero = '';
$k = 7-strlen($i);
for ($j = $k; $j >0; $j--) {
$zero .= 0;
}
echo $zero.$i.'<br>';
}
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)})</code></pre>
<h3>判断远程图片是否存在</h3>
<pre><code class="php">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;
}
}</code></pre>
<h3>检测函数类型</h3>
<pre><code class="php">
function getType(value){ //基本上可以返回所有的类型,不论你是自定义还是原生
return Object.prototype.toString.call(value).match(/\s{1}(\w+)/)[1];
}
let obj = new Object();
console.log(getType(obj)); //"Object"</code></pre>
<h3>moment.js时间处理</h3>
<pre><code class="php">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"]
</code></pre>
<h3>php中文正则匹配</h3>
<pre><code class="php">php中文正则匹配$str = "one中国你好two";
$preg = "/\P{Han}+/u";
$result = preg_replace($preg, '', $str);
var_dump($result); //string(12) "中国你好" p小写是匹配汉字,P大写是匹配非汉字</code></pre>
<h3>生成6位的数字验证码</h3>
<pre><code class="php">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));</code></pre>
<h3>16进制颜色代码生成</h3>
<pre><code class="php">
(function(){
return '#'+('00000'+(Math.random()*0x1000000<<0).toString(16)).slice(-6);
})()</code></pre>
<h3>php 模拟 tail -f</h3>
<pre><code class="php">$handle = popen("tail -f /var/log/nginx/access.log 2>&1", 'r');
while(!feof($handle)) {
$buffer = fgets($handle);
echo "$buffer\n";
flush();
}
pclose($handle);
</code></pre>
<h3>mysql distinct</h3>
<pre><code class="php">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</code></pre>
<h3>php下载文件</h3>
<pre><code class="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';
}
</code></pre>
<h3>javascript sort 排序</h3>
<pre><code class="php">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);
</code></pre>
<h3>javascript date</h3>
<pre><code class="php">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</code></pre>
<h3>javascript lastIndex</h3>
<pre><code class="php">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"]
}</code></pre>
<h3>微信浏览器禁止页面下拉查看网址</h3>
<pre><code class="php">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();
}
});</code></pre>
<h3>laravel 为 VerifyCsrfToken 添加过滤条件</h3>
<pre><code class="php">//修改 app/Http/Middleware/VerifyCsrfToken.php
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;
use Closure;
class VerifyCsrfToken extends BaseVerifier
{
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array
*/
protected $except = [
//
];
public function handle($request, Closure $next)
{
// 如果是来自 api 域名,就跳过检查
if ($_SERVER['SERVER_NAME'] != config('api.domain'))
{
return parent::handle($request, $next);
}
return $next($request);
}
}</code></pre>
<h3>switch 字符串和数字会隐式转换比较</h3>
<pre><code class="php">
$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;
}</code></pre>
<h3>输出调试信息</h3>
<pre><code class="php">
function log(msg){
var $body = document.querySelector('body');
if( !$body.querySelector('.info_wz_852') ){
$body.innerHTML += '<div class="info_wz_852" style="position:fixed;top:0;left:0;z-index:99999; background:#000;color:#f00;"></div>';
}
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 += '<p>['+minute+':'+second+'] '+loc+'</p><p>'+msg+'</p><br/>';
}
}</code></pre>
<h3>对象数组互转方法</h3>
<pre><code class="php">/**
* 数组转换对象
*
* @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;
}</code></pre>
<h3>javascript数组随机</h3>
<pre><code class="php">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)
}</code></pre>
<h3>php生成不重复字符串</h3>
<p><code>echo sprintf('%x',crc32(microtime()));</code></p>
<h3>PHP 随机用户名账号</h3>
<pre><code class="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;
}</code></pre>
<h3>一个操作中对 Redis 服务器执行多个命令</h3>
<pre><code class="php">Redis::pipeline(function ($pipe) {
for ($i = 0; $i < 1000; $i++) {
$pipe->set("key:$i", $i);
}
});</code></pre>
<h3>中文拼音排序</h3>
<pre><code class="php">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']]
['萃', '孚', '骅', '瀚', '珈', '迦', '恺', '鹭', '泸', '岷', '濮', '榕', '沱', '鑫', '浔', '怡', '兖', '柘']</code></pre>
<h3>php 金额每三位加逗号分隔</h3>
<pre><code class="php">//money_format
>>> strrev(implode(',', str_split(strrev('434353222323443'), 3)) )
=> "434,353,222,323,443"</code></pre>
<h3>php时间格式化</h3>
<pre><code class="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;
}
}</code></pre>
<h3>html写入word</h3>
<pre><code class="php">function word($data,$fileName=''){
if(empty($data)) return '';
$data='<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microsoft-com:office:word" xmlns="http://www.w3.org/TR/REC-html40">'.$data.'</html>';
if(empty($fileName)) $fileName=date('YmdHis').'.doc';
$fp=fopen($fileName,'wb');
fwrite($fp,$data);
fclose($fp);
}
$str = '<h2>hello daye</h2>';
word($str);
</code></pre>
<h3>一行代码可以看到所有页面元素</h3>
<p><code>[].forEach.call($$("*"),function(a){a.style.outline="1px solid #"+(~~(Math.random()*(1<<24))).toString(16)})</code><br><a href="https://segmentfault.com/a/1190000002784965">https://segmentfault.com/a/11...</a><br><a href="https://link.segmentfault.com/?enc=Kk5FP4kUoqucePhWM8uSww%3D%3D.Y%2BkkjKs%2FVkVNJwlSR9riqm9dQvSXcKd%2BPCpZPON3V%2B6rk2A2t2%2B2ti1ZzbT74PFn" rel="nofollow">http://blog.tanteng.me/2015/1...</a><br><a href="https://link.segmentfault.com/?enc=1hZnL5DR1d7RzG%2FXi1xKPw%3D%3D.sahZoFU%2BEa25c4MSkuGNtC194%2FFgWZ4QPLELcZF1vFjeatLVBsS21nBScbH5XafL0rBa8rDrZRGf7uXJX%2FaAnw%3D%3D" rel="nofollow">http://joebon.cc/date-cross-b...</a><br><a href="https://segmentfault.com/a/1190000005116655">https://segmentfault.com/a/11...</a><br><a href="https://segmentfault.com/q/1010000005070166">https://segmentfault.com/q/10...</a><br><a href="https://link.segmentfault.com/?enc=qDDXplltnJH5w1o%2B%2FqLWsQ%3D%3D.C2GmwYdUjMjURZlqDbezdRzQ7Tk%2FskilBctQcXBvdEsuDoht95T7rj3FVOCerkRDoBzV%2BppncS2yqGDcHY1S4iTGC0ANFAt6PeQpOfzzzJqlUpsRPfMKY4qVyp%2FJHvL4jienKNa2%2BNgUxg6PfkZkwvk%2FVou4B6ZuTgT3qKFJ1un3ALUY5ys43BZ3gpNfkQdv0944zmozVkiz8PeVImeONL27xnh2yAqLTq6fSFYxnhI%3D" rel="nofollow">https://www.zhihu.com/questio...</a><br><a href="https://link.segmentfault.com/?enc=rkF%2BXwEy0FywQIEE8xlq2Q%3D%3D.mBATHFwVLaAi2yFzkoB927r6FTqeldSIgqNrOcrPKzc%3D" rel="nofollow">http://t.cn/RqgIMWa</a><br><a href="https://link.segmentfault.com/?enc=GWjNnoCpQVEC73ul0xQxVQ%3D%3D.9Cp28iFhxwgeUIagPuLQcbwgtoYywTfGAjQ3ZykQ7Yw%3D" rel="nofollow">http://t.cn/h4tDfg</a><br><a href="https://link.segmentfault.com/?enc=22O8ms9wVt1vzolRGwyndQ%3D%3D.vU9Xne0Ho6nqjvi%2BAp58LGN4wk1BEt0ElaRhg4JSQRY%3D" rel="nofollow">http://div.io/topic/1610</a><br><a href="https://link.segmentfault.com/?enc=vB0SuUMJc%2FJ8I5ajXe8GOA%3D%3D.SXoQHuqRcTtVtKlPCP7COJTlcKP9paGkz9yaUh1KUcEJZF8NoH9Zmv8BIP4CIVqvjSX%2FjAXpe2O5cMI7TDQxKg%3D%3D" rel="nofollow">https://www.talkingcoder.com/...</a><br><a href="https://link.segmentfault.com/?enc=98yW87MKklUl702WqHvVPg%3D%3D.Lkemq7SH5cdnOjl%2By0V8rT9moKYUxCtfXA1%2Bk7Zc7AMIHZZ8YTvZ0oETEXQ0Cbmcj1tVH7lvy3vawL1KGt7cQN89Hjb4vCJrFeJnjMShoM4%3D" rel="nofollow">http://www.w3cfuns.com/notes/...</a><br><a href="https://link.segmentfault.com/?enc=aWXaENCtjVJ38gd8S6%2F9xw%3D%3D.U3WMFAbpU9WigbCsr4i9s6WJ821hEfHqEJrDH6G%2FIfXK0RZidyeYfnRPIXyxyCfMsdZhyfOOlvDCmSh6vvcq6w%3D%3D" rel="nofollow">http://www.cnblogs.com/shocke...</a></p>
laravel artisan command
https://segmentfault.com/a/1190000004404823
2016-02-02T15:26:33+08:00
2016-02-02T15:26:33+08:00
苏生不惑
https://segmentfault.com/u/sushengbuhuo
0
<p><a href="https://link.segmentfault.com/?enc=ICs7EMgX%2FwtW9MWNf51TVw%3D%3D.XKqEHdy6oOCglZy5S6uQ23Zdq762CMyb%2FEh3s3vaWBMZg1Zd6t7r1x5Nw4dFPI1Hg8L5%2BZHtTZNqDFgTXOOH8w%3D%3D" rel="nofollow">文档地址</a><br>1.创建命令类<br>php artisan make:console user#生成文件user.php<br>2.编写文件</p>
<pre><code class="php"><?php namespace App\Console\Commands;
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
use App\Models\Attention;
use RedisFacade;
class User extends Command
{
/**
* The console command name.
*自定义命令的 名称
* @var string
*/
protected $name = 'user';
/**
* The console command description.
*
* @var string
*/
protected $description = 'User';
/**
* Execute the console command.
*自定义命令被执行时,将会调用 fire 方法
* @return mixed
*/
public function fire()
{
$action = 'action' . ucfirst($this->argument('action'));
if (method_exists($this, $action)) {
$this->$action();
return false;
}
$this->error('action参数为空.');
}
/**
* 用户关注关系更新到redis
* @return mixed #php artisan user -t redis -s 100 --usleep 0 attention
*/
protected function actionAttention()
{
if ($this->option('target') != 'redis') {
$this->error('target 参数错误.');
return false;
}
$redis = RedisFacade::connection();
$usleep = $this->option('usleep');
$limit = $this->option('size');
$minId = 0;
while (true) {
$attention = Attention::where('id', '>', $minId)
->select('id', 'user_id', 'at_id', 'created_at')
->orderBy('id')
->take($limit)
->get();
$selectCount = count($attention);
if (!$selectCount) {
break;
}
//批量操作
$redis->pipeline(function($pipe) use($attention) {
foreach ($attention as $v) {
$pipe->hSet('follows:list:' . $v['user_id'], $v['at_id'], strtotime($v['created_at']));
$pipe->hSet('fans:list:' . $v['at_id'], $v['user_id'], strtotime($v['created_at']));
}
});
if ($selectCount < $limit) {
break;
}
//最后一个id
$minId = $attention->last()->id;
unset($attention);
if ($usleep > 0) {
usleep($usleep);
}
}
$this->info('完成.');
}
/**
* Get the console command arguments.
*
* @return array
*/
protected function getArguments()
{
return [
['action', InputArgument::REQUIRED, 'Action name, eg: sync'],
];
}
/**
* Get the console command options.
*默认参数可通过执行php artisan user -h 来查看
* @return array
*/
protected function getOptions()
{
return [
['target', 't', InputOption::VALUE_OPTIONAL, 'Sync target', 'redis'],
['size', 's', InputOption::VALUE_OPTIONAL, 'Loop size', '100'],
['usleep', null, InputOption::VALUE_OPTIONAL, 'Loop usleep', '0'],
];
}
}
</code></pre>
<p>3.注册一个 Artisan 命令<br>vi app/Console/Kernel.php</p>
<pre><code class="php">protected $commands = [
'App\Console\Commands\User',
];</code></pre>
创建packagist composer库
https://segmentfault.com/a/1190000004294540
2016-01-12T19:44:03+08:00
2016-01-12T19:44:03+08:00
苏生不惑
https://segmentfault.com/u/sushengbuhuo
2
<p>1.mkdir app && cd app<br>2.composer init<br>3.vi composer.json</p>
<pre><code class="php">{
"name": "yourname/yourpro",
"description": "desc",
"authors": [{
"name": "yourname",
"email": "yourname@gmail.com"
}],
"require": {},
"autoload": {
"classmap": [
"lib/"
]
}
}</code></pre>
<p>4.创建git库yourname/yourpro<br>5.git remote add origin git@github.com:yourname/yourpro 设置公钥略过<br>5.git add .&& git commit -am "init" && git pull orgin master && git push orgin master<br>6.创建tag composer包版本来自于git分支和tag,分支代表dev版本(除master外),tag代表stable版本<br>7.git tag 1.0 && git push origin --tags<br>8.登录<a href="https://link.segmentfault.com/?enc=NLw9eX%2BFjUlwpxePkFlp4Q%3D%3D.tVip2QlrCp6CD8PRwe4neBIEmYkLgOLzwVyrdfb1mGU%3D" rel="nofollow">https://packagist.org/</a> 点击由上角的submit提交git仓库的地址<br>9.添加 GitHub Service Hook domain 指向packagist的地址</p>
<p><img src="/img/bVsbmv" alt="clipboard.png" title="clipboard.png"><br>10.安装库 composer require 'yourname/yourpro:1.0.0<br> 如果报错,执行composer update nothing:</p>
<pre><code class="php">Potential causes:
- A typo in the package name
- The package is not available in a stable-enough version according to your min
imum-stability setting
see <https://groups.google.com/d/topic/composer-dev/_g3ASeIFlrc/discussion> f
or more details.</code></pre>
支付宝app支付
https://segmentfault.com/a/1190000004182904
2015-12-22T16:21:33+08:00
2015-12-22T16:21:33+08:00
苏生不惑
https://segmentfault.com/u/sushengbuhuo
2
<p><a href="https://link.segmentfault.com/?enc=rAFDt6ZTbXqQtZXuycXRAQ%3D%3D.7GGHTd1CDEw4l7BOuhBvSs3qKBOnAgBQlDyh5DBcMiOQN7unTdDEprx5Bu3ob7QFNF5fGMraDarSlY9oCZVfySBlAtFd3OoEukyWoTd78vM%3D" rel="nofollow">RSA密钥生成命令</a><br>生成RSA私钥<br>openssl>genrsa -out rsa_private_key.pem 1024<br>生成RSA公钥<br>openssl>rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem<br>将RSA私钥转换成PKCS8格式<br>openssl>pkcs8 -topk8 -inform PEM -in rsa_private_key.pem -outform PEM -nocrypt</p>
<p>注意:“>”符号后面的才是需要输入的命令。<br><a href="https://link.segmentfault.com/?enc=IMvGP%2FDO%2BZDx34zE6pk2TQ%3D%3D.lRGoXsrm7%2FBPKWOgrAWqzt9QlBF1dvNq%2BmOAHVRz7%2BhaiZ8QtKEAYw9CWZ2kb%2BqBpXB7pXiBGLZWD%2FfkKcCpFDXQWwhRC473TkqhAbjxztZyUHMU6GOUkienwFIcVRislEKEUIj09N1P1S%2F4JsSD1w%3D%3D" rel="nofollow">PID和密钥管理</a></p>
<p><img src="/img/bVrIrL" alt="clipboard.png" title="clipboard.png"></p>
<p><img src="/img/bVrIjD" alt="clipboard.png" title="clipboard.png"></p>
<p>返回给ios或Android下订单的参数</p>
<pre><code class="php"> [
'orderid' => 201512221234567890,
'partner' => config('services.alipay.pid'),
'seller' => config('services.alipay.email'),
'privateKey'=> config('services.alipay.private_key'),#生成的pkcs8格式,去除开头结尾的-----BEGIN PRIVATE KEY----- -----END PRIVATE KEY-----
'amount' => $fee,
'subject' => $subject,
'body' => $subject,
'callback' => 'http:xxx.com/app'
]</code></pre>
<p>回调需要参数:<a href="https://link.segmentfault.com/?enc=IGC%2FgUYKnIrF%2FaztEXgAAg%3D%3D.4MDzn%2BB34AKGQeOZZ7mTJNnYYDtBkVgE4cRCsBU%2BO7CjPXXwFf8ubzgKoZXyqhHzuLW4QfQgDLlyIF7mL5aYgsvB6DvqD1wWZhqBmJ08piXqfoPRouLwgXzUbjhienMW" rel="nofollow">支付宝公钥</a>,pid,key(需要支付密码查看)<br><a href="https://link.segmentfault.com/?enc=LiMQsbf15FKpaMxbwcMQmw%3D%3D.KPAozr4WxJVWRyan7IrSozvx7I92a4%2FuiJFERlOIGr4mfd6Cdajem7fGbvdcYWkX4k0%2Bfg600%2Fi0rpOs14JBdjhd3%2BNk9QOmYoW6r46aOVs%3D" rel="nofollow">上传上面自己生成的公钥</a>(去除换行)返回支付宝公钥做如下处理:<br><img src="/img/bVrIrr" alt="clipboard.png" title="clipboard.png"></p>
<p><img src="/img/bVrIrz" alt="clipboard.png" title="clipboard.png"><br>返回的支付宝公钥头部加上-----BEGIN PUBLIC KEY----- 放在自己项目目录</p>
<p>登录支付宝账号,签约申请“移动快捷支付”功能,操作流程参考:<br><a href="https://link.segmentfault.com/?enc=ulkH0xSlIMBZJlLEXYAjaQ%3D%3D.Nwv6yTtCEBYoysWn6anA49G5jq8PSCxbA46LEFhwC1JrTfFQmfbchc6IQGwDqQcx" rel="nofollow">支付宝帮助中心</a><br>获取PID,:<br>获取合作者身份ID<br>生成密钥(公钥和私钥),并提交到支付宝,参考教程:<br><a href="https://link.segmentfault.com/?enc=PrHgPg3z%2FS6CyKMvXmRk4Q%3D%3D.eIr9jDTTaKvhaZx4bZznReiAWeSpMeUssCXYIuBmUh3MGHQx4ssSHO6a5skqsve3" rel="nofollow">生成RSA密钥</a><br><a href="https://link.segmentfault.com/?enc=ilfb%2BYCLMCzq3iN0UIYrlw%3D%3D.IeEhWxN0SGWkcPmcsNxtozhSFbliwyVW3rtOVUcRrxBpX8MMp%2F34zBScr7Q7%2BddO" rel="nofollow">上传公钥</a></p>
<hr>
<p><a href="https://link.segmentfault.com/?enc=yl%2FVQAlqFWshg7OITLhrJw%3D%3D.Rn%2FjlYG4oqLmKYNOQ7rYjw7rL0FlfpcV73jmoag%2BZseeacol3pYVEV2I9LlFFmWuwqqajO%2BCF%2FH8VMaf1KHjQ5Iiv%2FRbxtSnDFKBPEdfKwE%3D" rel="nofollow">参考开源示例代码github-支付宝</a></p>
微信app支付
https://segmentfault.com/a/1190000004087670
2015-12-03T08:21:46+08:00
2015-12-03T08:21:46+08:00
苏生不惑
https://segmentfault.com/u/sushengbuhuo
1
<p><a href="https://link.segmentfault.com/?enc=QxkV%2BRnHfmXe5M1HAi3vyg%3D%3D.rrIDgvQ9DTl1kRDqOdT6wbt6VQAEMrVfav%2FPAmmeXsaYUbSmf3unyGpbAp9uteUgqKnVTmNvG15210f5W7%2Bbng%3D%3D" rel="nofollow">文档</a><br>注:开放平台的微信支付和公众号的微信支付是不一样的,公众平台和开放平台的支付申请下来之后会有各自对应的商户平台账号</p>
<pre><code class="php">function wechat($appid,$mchid,$appkey,$cert_path,$key_path,$order_id,$openid,$amount,$desc){
$arr = [
'mch_appid'=>$appid,//注意区分公众号和app商户号不同
'mchid'=>$mchid,
'nonce_str'=>str_random(32),//随机数
'partner_trade_no'=>$order_id,//自己定义一个不重复订单号
'openid'=>$openid,//微信openid 通过微信授权登录获取
'check_name'=>'NO_CHECK',
'amount'=>$amount*100,//注意这里传给微信的单位是分
'desc'=>$desc,
'spbill_create_ip'=>\Request::getClientIp(),
'sign'=>'',
];
ksort($arr);
$sign="";
foreach ($arr as $key => $value) {
if($value && $key!="sign" && $key!="key"){
$sign.=$key."=".$value."&";
}
}
$sign.="key=".$appkey;//商户后台自定义的
$arr['sign'] = strtoupper(md5($sign));
$xml = "<xml>";
foreach ($arr as $key=>$val)
{
if (is_numeric($val))
{
$xml.="<".$key.">".$val."</".$key.">";
}
else
$xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
}
$xml.="</xml>";
$ch = curl_init();
//超时时间
curl_setopt($ch,CURLOPT_TIMEOUT,60);
curl_setopt($ch,CURLOPT_URL,'https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers');
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);
//默认格式为PEM
curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
curl_setopt($ch,CURLOPT_SSLCERT,$cert_path);//注意区分公众号和app商户号的证书不同,需要到pay.weixin.qq.com后台下载
curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
curl_setopt($ch,CURLOPT_SSLKEY,$key_path);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml'));
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS,$xml);
$data = curl_exec($ch);
$data = json_decode(json_encode(simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
curl_close($ch);
return $data;//$data['return_code'] == 'SUCCESS' && $data['result_code'] == 'SUCCESS' 支付成功
}
}</code></pre>
<p><a href="https://segmentfault.com/q/1010000007365200">微信上传文件</a></p>
<pre><code class="php"> function https_request($url,$type="get",$res="json",$data = ''){
//1.初始化curl
$curl = curl_init();
//2.设置curl的参数
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,2);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
if ($type == "post"){
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
//3.采集
$output = curl_exec($curl);
//4.关闭
curl_close($curl);
if ($res == 'json') {
return json_decode($output,true);
}
}
function getWxAccessToken(){
if ( $_SESSION['access_token'] && $_SESSION['expire_time'] > time() ) {
//未过期
return $_SESSION['access_token'];
}else {
$appid = "我的id";
$appsecret = "我的appsecret ";
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appsecret;
$res =$this->https_request($url,'get','json');
$access_token = $res["access_token"];
//将重新获取到的access_token存到session里
$_SESSION['access_token']=$access_token;
$_SESSION['expire_time']=time()+7200;
return $access_token;
}
}
//上传图片素材(该方法只能获取到图片的URL)
function addMaterialUrl() {
$access_token = $this->getWxAccessToken();
$url = "https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=".$access_token;
$filename = '我是图片';
$data=array("media"=>'@'. $filename);
$res=$this->https_request( $url ,'post', 'json', $data);
//dump($res); exit();
return $res['url'];
}
php5.6加上curl_setopt ($curl, CURLOPT_SAFE_UPLOAD, false);或者直接"media" => new CURLFile(realpath($real_path)), https://segmentfault.com/a/1190000000725185 </code></pre>
<p>附:<br><a href="https://link.segmentfault.com/?enc=clbsjN37oRAN9utUyiIJUQ%3D%3D.dZF%2BRH3s4IO8xWRjmOg0YByhpMakO4Pw7HbfmgAs%2F1zcA8IiRcDDWWUrz4Pjn3u7o5z38kh903zHwSdfyWj5cg%3D%3D" rel="nofollow">https://youqingkui.me/note/e5...</a><br><a href="https://link.segmentfault.com/?enc=knVhBvw47J5qMGQRBlrcIQ%3D%3D.d3gk32NGV6ewh5eiAAJev%2B%2FdV6%2BwjhvvzUChZa7fEfwNs6Ylv%2FHXeXy%2B3ZPaf4vU" rel="nofollow">python版微信支付</a><br><a href="https://link.segmentfault.com/?enc=sVVRZtSi7w1nRtqk0J1GWg%3D%3D.jpfIjGfskl2n4oB7crozAQripnecwaFvAekkcShsydKiiyY46e6NBQXyxSkOy%2FeO%2F1IUbNcBgWVOotpViLz9Og%3D%3D" rel="nofollow">http://bblove.me/2015/10/25/w...</a><br><a href="https://link.segmentfault.com/?enc=97HU8tnmgDU0llKFDYOcoQ%3D%3D.2kp8wRCsW9t96MzEPSWzf2ls1uxfpY06HrL443VLJXKe9%2BTLKW783Opl79dHKuy97pPreNPt35QxaUNbcVcN1g%3D%3D" rel="nofollow">微信APP支付服务端php sdk开发教程</a><br><a href="https://link.segmentfault.com/?enc=ZQGnXPlJnYDXo3nD%2B0zX8Q%3D%3D.F3m9u98VABI8KoSsZv0ticG%2B4LyG1d0TL%2BKGLzZzp8nGzN31MzUPDW%2BADvSUEw%2Bp" rel="nofollow">https://github.com/fanhefan/w...</a><br><a href="https://link.segmentfault.com/?enc=NMHAWFQR8jAuRvm%2F6G4NEQ%3D%3D.LwGH8Ucum3UBzvBD81mwNXVsONDQXSWkXDTCgYv9JRhZ7L7f2VIUXJGk5jsG2h5F" rel="nofollow">微信红包API接口</a><br><a href="https://link.segmentfault.com/?enc=CDkVRZXbWx2qwh%2FhZchfrg%3D%3D.V3BJTDMWGIrKMJbmrk67o9Bl3Xp3KH7RJfjG4OFwmaw%3D" rel="nofollow">http://jeffchen.sinaapp.com/</a><br><a href="https://link.segmentfault.com/?enc=%2BgmpRfFY%2BkM0n3hV9xTSPA%3D%3D.YGmbo2hWSxv190SJI3RFKbo%2BGOyk%2BUdJwCb16d%2FLrVyvkrGC5JwKEsCfgixReFKeVHvIhZZAY4JN1XKEpboOgVmvsBgtTDCmllY%2Bar7sAOM%3D" rel="nofollow">http://tao.logdown.com/posts/...</a><br><a href="https://segmentfault.com/a/1190000006886519?_ea=1245770">微信支付 一步一个坑的APP支付</a></p>