Hank X Front-End Engineer Run, Build, Enjoy

How to copy image and text to clipboard with JavaScript

I used to saw my colleague add a 30kb lib only to implement a copy function that when user clicks on a text, copy it to the clipboard.

And I also saw someone still trying to use flash or Clipboard lib to do same thing.

Here is how to copy text to your clipboard with JavaScript

with just several lines of code. And it’s cross browser and device. No need to any 3rd party lib.

function copyToClipboard(text){
 const ta = document.createElement('textarea');
 ta.value = this.url;
 document.body.appendChild(ta);
 //hide it
 ta.style.padding = 0;
 ta.style.border = 'none';
 ta.style.outline = 'none';
 ta.style.boxShadow = 'none';
 //select the text
 ta.focus();
 ta.select();
 document.execCommand('copy');
 document.body.removeChild(ta);
}

it’s very simple, you just append an invisible textarea to the page, set value as the text you want to copy, and run document.execCommand('copy'). Then remove the textarea from the page.

here is how to copy image to your clipboard with JavaScript

Note that this one only works on Chrome and Edge right now (2020-10) https://caniuse.com/mdn-api_clipboarditem

This requires you to use canvas to port image to blob first.

function imageToBlob(imageURL) {
  const img = new Image;
  const c = document.createElement("canvas");
  const ctx = c.getContext("2d");
  img.crossOrigin = "";
  img.src = imageURL;
  return new Promise(resolve => {
    img.onload = function () {
      c.width = this.naturalWidth;
      c.height = this.naturalHeight;
      ctx.drawImage(this, 0, 0);
      c.toBlob((blob) => {
        // here the image is a blob
        resolve(blob)
      }, "image/png", 0.75);
    };
  })
}

Then use the Clipboard API to do the magic


async function copyImage(imageURL){
  const blob = await imageToBlob(imageURL)
  const item = new ClipboardItem({ "image/png": blob });
  navigator.clipboard.write([item]);
}

Simple as that.

如何在电脑上调试手机真机网页以及微信浏览器网页

遇到个需求需要调试在微信中打开的网页。之前没有做过,搜了一圈那个所谓的在微信对话框中打开debugx5.qq.com的方法已经过时无用, 打开就显示你所使用对内核非X5内核。至于TBStool更是在2017年就已经停止更新,打开就闪退,浪费时间安装。

看来因为开发人员对QQ搞出来的X5内核怨声载道,所以微信不得不妥协,弃用了X5内核作为内置浏览器内核了。

至于spy-debugger等工具,我嫌麻烦也没装。

找半天找不到有用的方法,好在同样的问题在手机上的Chrome里面打开也存在,于是就想先在Chrome里调试,万一能一起修复了呢。

没想到就发现了Chrome调试工具居然也可以调试微信浏览器里打开的页面。看起来微信内建浏览器也采用了Chromium内核了。

以下步骤同时适用于在电脑上调试手机浏览器网页调试和微信内建浏览器网页, 目前只限Android系统。iPhone还没去看。

  • 打开手机的开发者模式,这个各个手机打开方式都差不多,通过多次点击版本号来开启。

  • 在开发者模式里面打开 USB 调试功能

  • 把你要调试的网址发送到微信对话框里,然后点击打开

  • 将手机通过USB数据线连接到电脑

  • 在电脑上打开Chrome浏览器

  • 新建一个标签页,输入网址 chrome://inspect/#devices。以前你需要在 Chrome 的开发者工具里面通过点击多个菜单来打开,Chrome现在将这个页面独立出来了,体验更佳。

  • 这时候你的手机应该会收到 允许当前连接的设备访问手机数据 的通知,点击允许即可

  • 在电脑端 Chrome 的 chrome://inspect/#devices 里面就应该能看到你手机 Chrome 里面打开的页面了

  • 同时如果你已经在微信内建浏览器里打开了网页,你应该也能看到一个名为 com.tencent.mm 的浏览器里面打开了一个页面。

  • 点击网址下面的 inspect 就可以打开调试页面,其拥有电脑端Chrome开发工具的几乎所有调试功能。

不得不说发现这点还是挺惊喜的。

Shout out to Jetbrains IDE

I write this post because Jetbrains just gave me full access to all its tools as an open source project developer. So I just want to say thanks with this post.

After I tried Webstorm for several days, I found it’s much better than VS Code.

What am I saying, Webstorm is a commercial software, while VS Code is open source and free. 😅

Anyway, I found myself coding much faster with Webstorm and other Jetbrains tools. Like, I don’t have to pick and configure all those extensions carefully to make so that it won’t popup css selector when I’m coding JavaScript. Webstorm also has built-in spell check, it’s like a life saver for non-native English speaker.

Some people might think that VS code eats less RAM than Webstorm, also faster when launching. While my computer has 32 GB RAM and i7, so I never need to care about the RAM. Plus, if you install and enable too many extensions, you can also notice that VS Code takes a lot of RAM too.

And I barely need to code some stuff within 30 sec, so the launching time is not an issue to me too. This is not mean I’m not gonna use VS Code, it’s still great, especially it can edit any programming languages, with extensions.

Its price is also reasonable, for individual, most of the tools are between $59 - $69 for the first year, cheaper for the next years.

It also has many free plans, students, teachers, etc. If you are an active open source developer, you can even ask for a free license.

Like me, since I have this small open source project one click extensions manager, it has more than 30k users.

Jetbrains gives me full access to all its tools for a year, and can be re-subscribed every year.

So if you also have open source project, try to apply for its license and try this great IDE :D

Use git archive to zip your source code

To zip compiled project file is easy, normally I just use archivejs, write a small nodejs script, and then add a script in package.json.

And then I need to zip the source code only. Exclude the dist folder, the huge node_modules folder and other folders.

Basically just source code and exclude everything in .gitignore file.

I tried to use archivejs’s glob api. Like so:

archive.glob('**', {
  ignore: ['folder/**', 'file']
})

But I could not make it works, it either zip nothing or zip everything in my folder, I think it’s because the path that I set is not correct. And I don’t want to spend too much time on reading and exploring archivejs’s api doc.

So I came to use zip command in terminal. To use it is very simple, just use -x to exclude file, like this

zip -r output.zip directory -x \*\*/\*/node_modules/\*

Which is great. But the command is too long and if there are many files you want to exclude, you will need to write down them every time.

At the same time I found that with git archive I can do this easily. so just run

git archive --format=zip HEAD -o zipfile.zip

it will pack all your source code into zip file, exclude everything in the .gitignore file. Super neat.

how to use jQuery with TypeScript

It’s 2020, why do you still need to use jQuery?

Yeah, jQuery has 53.8k stars on Github. And still, there are more than 97% of websites are using it.

Even if you don’t want to use it in your fancy project. It’s still a good choice to use it when you are building a demo, prototype, or some small side project. I mean, when you are configuring your fancy project with wepack, react/vue/angular, babel, I already have done a small page which can send request to the API and show the result on the page.

Anyway, if you want to use jQuery with TypeScript. Here are the steps that you need to do.

add jquery

yarn add jquery

add jquery types

this will suppress VS Code complains that it can not find jquery types

yarn add @types/jquery

config tsconfig.json to suppress another warning message

can only be default-imported using the ‘allowSyntheticDefaultImports’ flagts(1259) index.d.ts(35, 1): This module is declared with using ‘export =’, and can only be used with a default import when using the ‘allowSyntheticDefaultImports’ flag.

goto your tsconfig.json file, add one line in your the compilerOptions block. if you don’t have this tsconfig file in your project’s root folder, then create one.

"allowSyntheticDefaultImports": true,

Then you can use jquery in your ts file like this:

import $ from 'jquery'

$.ajax().then().catch().finnally()

用 Taro 和 Vue 写了一个微信小程序

最近尝试写微信小程序,毕竟是现在的趋势。然后发现因为入场太晚,各种轮子已经造得遍地飞了。比如这里有一个框架,出自京东,叫做Taro,它的目的是写一份代码,就可以在诸如微信、支付宝、字节跳动(它家的什么app支持小程序?)等端作为小程序运行。

于是拿来试了以下。我本来只熟悉Vue的,这个Taro原生支持React,代码风格也都是React的样式。虽说现在3.0以上支持Vue了,可是要做的时候还是有一些转换成本。

然后框架本身也还存在一些bug,不过一次编写,多端运行还是挺有意思的。

项目地址:https://github.com/hankxdev/taro-v2ex

以下内容来自README:

Taro + Taro-UI + Vue + V2EX API 多端小程序

如题,这是一个使用了这几个技术的练习项目。我是第一次使用Taro和写微信小程序。Taro官方有个渐进式教程,使用的也是V2EX的API。

技术栈:

本地运行和测试

  • yarn
  • yarn dev:weapp
  • 因为调用了v2ex 的API,用自己的微信小程序ID的话,需要去后台设置一下域名白名单,否则 API 调用会失败。

比教程多了一些的是:

  • 代码完整。官方教程的代码比较零散,甚至有些跑不通。
  • 用户详情页面和节点详情页面
  • 全部使用真正的V2EX API 而不是使用自定义数据
  • 自定义 Tabbar
  • 使用了Taro-UI来做界面

项目存在的问题:

以下是我知道的主要问题。大佬们如果发现新问题或者知道这些问题的答案,欢迎提 issues 或者 PR, 望不吝赐教。

  • 几个页面在切换的时候并不会刷新。这里怀疑是Taro的bug,文档中写的 onShow 方法并不能在页面显示的时候被成功调用。
  • 不怎么好看。因为主要用来熟悉Taro以及微信小程序和多端小程序开发,因此并未在界面上花功夫,几乎没有怎么写样式。使用的全都是Taro-UI 默认的组件。
  • 有点卡。一方面v2ex并未提供分页的API。有些 endpoints 诸如获得节点列表、帖子列表等,都是一大堆上千条数据一下子全返回。网络慢的时候导致卡顿更加明显。
  • TypeScript 使用并不规范。我很少写 TypeScript。也一直懒得学,因此基本上都是用JavaScript 的写法在写 TypeScript。同样,写好或者学习 TypeScript 也并不是我写本项目的目的。略过。
  • CustomTabBar 的实现并不规范。现在的做法是写一个 CustomTabBar, 然后放置进每个页面中。正确的做法应该是。
    1. app.config.ts 中的tabList 里,设置 custom: true
    2. src 目录下新建 custome-tab-bar 文件夹
    3. custome-tab-bar 下面添加 index.js,index.wxml, index.wxss 来自定义 tabbar 的样式和行为。 需要注意的是,这里不能直接写 index.vue,编译不出来的。

hot

How to fix Git show all file as modified in WSL

Solution

If you open your code in Windows, and run git in WSL bash, you will have a big chance to meet an issue that git status shows all your file get modified. To fix the issue, run this in WSL bash:

git config --global core.autocrlf true

Normally I use OSX, but today I have to go back to my Windows PC to try an extension on Edge.

I’m using WSL (that’s Windows Subsystem for Linux) to manage and build my projects.

After I cloned my repo from Github, I tried to create a new branch for Edge version. But after I ran git branch branchname , it told me that there were changes need to commit first.

So I ran git status, to check what’s been changed. Then I got this:

all files modified

This was a simple app. so it’s basically showing that every file got modified. But I hadn’t do anything to any file.

It’s because I was using git in WSL, but I opened files in Windows system. So the line ending is CRLF, but git thought it’s on Linux so the line should ends with LF.

So the fix command will tell git to use CRLF and line ending.

Change Ubuntu 20.04 update source to mirror site in China

Ubuntu 20.04 has been released for a while, its code is Focal Fossa. Again, if you are in China, better change the update source to mirror sites.

This post is just a copy from Change Ubuntu 18.04 update source to mirror site in China, and I just replaced the source url from thoes ones of 18.04 to 20.04

Here are several famous mirror sites. What you need todo is pick one from below and edit etc/apt/sources.list, replace the content in this file.

There are some links beend commented out.

  • starts withdeb-src is for source code, without them the speed would be even faster
  • the one with focal-proposed are just proposed updates, only enable them if you know the risk.

Better backup you etc/apt/sources.list before you do this

163 (netease)

source:http://mirrors.163.com/

deb http://mirrors.163.com/ubuntu/ focal main restricted universe multiverse
deb http://mirrors.163.com/ubuntu/ focal-security main restricted universe multiverse
deb http://mirrors.163.com/ubuntu/ focal-updates main restricted universe multiverse
deb http://mirrors.163.com/ubuntu/ focal-backports main restricted universe multiverse
# deb http://mirrors.163.com/ubuntu/ focal-proposed main restricted universe multiverse
# deb-src http://mirrors.163.com/ubuntu/ focal main restricted universe multiverse
# deb-src http://mirrors.163.com/ubuntu/ focal-security main restricted universe multiverse
# deb-src http://mirrors.163.com/ubuntu/ focal-updates main restricted universe multiverse
# deb-src http://mirrors.163.com/ubuntu/ focal-proposed main restricted universe multiverse
# deb-src http://mirrors.163.com/ubuntu/ focal-backports main restricted universe multiverse

alibaba (aliyun)

source:https://opsx.alibaba.com/mirror

deb http://mirrors.aliyun.com/ubuntu/ focal main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ focal-security main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ focal-updates main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ focal-backports main restricted universe multiverse
# deb http://mirrors.aliyun.com/ubuntu/ focal-proposed main restricted universe multiverse
# deb-src http://mirrors.aliyun.com/ubuntu/ focal main restricted universe multiverse
# deb-src http://mirrors.aliyun.com/ubuntu/ focal-security main restricted universe multiverse
# deb-src http://mirrors.aliyun.com/ubuntu/ focal-backports main restricted universe multiverse
# deb-src http://mirrors.aliyun.com/ubuntu/ focal-updates main restricted universe multiverse
# deb-src http://mirrors.aliyun.com/ubuntu/ focal-proposed main restricted universe multiverse

And here are also two Chinese university mirror, use them only if you are in Chinese university.

tsinghua university

deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ focal main restricted universe multiverse
deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ focal-updates main restricted universe multiverse
deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ focal-backports main restricted universe multiverse
deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ focal-security main restricted universe multiverse
# deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ focal-proposed main restricted universe multiverse
# deb-src https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ focal main restricted universe multiverse
# deb-src https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ focal-updates main restricted universe multiverse
# deb-src https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ focal-backports main restricted universe multiverse
# deb-src https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ focal-security main restricted universe multiverse
# deb-src https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ focal-proposed main restricted universe multiverse

ustc (university of science and technology of China)

deb https://mirrors.ustc.edu.cn/ubuntu/ focal main restricted universe multiverse
deb https://mirrors.ustc.edu.cn/ubuntu/ focal-updates main restricted universe multiverse
deb https://mirrors.ustc.edu.cn/ubuntu/ focal-backports main restricted universe multiverse
deb https://mirrors.ustc.edu.cn/ubuntu/ focal-security main restricted universe multiverse
# deb https://mirrors.ustc.edu.cn/ubuntu/ focal-proposed main restricted universe multiverse
# deb-src https://mirrors.ustc.edu.cn/ubuntu/ focal main restricted universe multiverse
# deb-src https://mirrors.ustc.edu.cn/ubuntu/ focal-updates main restricted universe multiverse
# deb-src https://mirrors.ustc.edu.cn/ubuntu/ focal-backports main restricted universe multiverse
# deb-src https://mirrors.ustc.edu.cn/ubuntu/ focal-security main restricted universe multiverse
# deb-src https://mirrors.ustc.edu.cn/ubuntu/ focal-proposed main restricted universe multiverse

Enjoy:)

How to fix You have to set a contact email in Chrome Web Store

I have multiple accounts in Chrome Web Store to manage multiple Chrome extensions.

Today I found that one of my extension one click extensions manager did not get updated as schedule. which is very abnormal because it’s scheduled by Github action, and the log shows that the latest version had been submitted to the store several days ago.

In the dashboard it’s telling me to add a contract email in my account so that I could publish it. And I already added it long time ago.

After several meaningless refreshes and clicking on the save button, I realized it might because of my other accounts. So I switched to other accounts and found there is one account without contact email. And the item got published once I fixed this issue.

So weird because it never asks me to add contact email before. And the store hint is so unclear, it needs you to add contact email on every account, not just the current one.

Honestly, the new Chrome web store dashboard is not as easy to use as the old one. Only the UI is fresher than before.

chrome web store asks for contact email

Also, got an email from Microsoft Edge team, they ask me to submit my extension to Edge store, as Edge is using Chromium now. So if you have published Chrome extension before, you can try to submit it to Edge store too. The process would take less than 30 min to do it.

And, the Edge store dashboard is hard to use too, especially if your extension surppots multiple language, you will need to set information like logo, screenshot, description for every language. insane, right?.

My First LEGO

Got a LEGO gift from an old friend. Finished it in two weeks :D Love it a lot.

LEGO Friends
LEGO Friends
LEGO Friends
LEGO Friends

安装了梅林固件的路由器开启SSH以及超频

部分路由器可以通过安装Merlin梅林固件来实现更多的自定义功能。安装更多第三方插件来让路由器变得更强大。

在软件自定义的时候不妨试试将路由器进行硬件超频来使其拥有更强劲的性能。

实现起来也非常简单,不过需要注意的是,超频可能会造成不可恢复的硬件损害,俗称变砖。超频前要三思,也不要妄图过分超频来让路由器硬件性能达到其不可能达到的等级。

要超频需要先登入路由器命令行。推荐使用SSH。Windows下使用puttty等你熟悉的SSH工具,macOS则直接用终端即可。

首先梅林默认是不开启SSH的。需要进入路由器管理界面——系统管理——SSH Daemon来开启。 设置如下:

merlin ssh

其中选项都非常清楚明白,按照个人所需设置即可。SSH key 可以让你登录的时候不用输入密码。也就是你登录路由器管理页面设置的密码。

然后在putty或者终端里输入如下命令来登入路由器命令行。命令里的用户名是你在浏览器中登录路由器管理页面的用户名。

ssh 用户名@192.168.50.1

一般梅林的默认路由器ip有两个,192.168.2.1或者192.168.50.1。根据你自己路由器的ip来更改以上命令登入。

如果你没设置SSH key的话,接下来需要输入密码了。

密码正确就进入路由器命令行了, 你会看到类似以下文字:

ASUSWRT-Merlin [路由器型号] [梅林版本] Tue Sep 25 12:04:55 UTC 2018
[用户名]@[路由器型号]:/tmp/home/root#

其中没有中文字的,这里只是说明这里字符代表的意思,你应该能看到你自己路由器的型号、版本、用户名等信息。

接下来运行以下命令:

nvram set clkfreq=1000,800

这里的1000是设置CPU频率,800是设置内存频率(800相当于1600)。不要改太大。一般建议CPU频率设置数值为默认频率加200就比较安全。性能也能得到较好提升。否则变砖甚至烧机得不偿失。

然后运行以下命令来提交更改。

nvram commit

最后运行reboot来重启路由器。

如果没什么问题,重启完成后路由器就超频成功了。

有时候会遇到路由器亮两个红灯无法正常启动的情况,不要慌,这不是变砖,只是启动失败。刷了梅林之后会经常遇到启动失败的问题。这时候只要给路由器断电,等几秒,再次按电源键启动即可。如果还是启动不了就再重启一次。多试几次一般都能成功启动。

实在不行只能重置。拿笔戳重置按钮30秒,然后继续按着重置按钮不动,重置电源启动30秒,再关闭电源30秒,最后再启动。传说中的30-30-30大法,重置成功就代表没变砖。

Use Husky to manage git hooks

Git hooks is a powerful tool to make your life easier.

It fires off custom scripts when certain important actions occur. one common scene like: you want to lint your code every time when you commit changes, so that your code has a good style and following your team’s code specification. Or you want to run test before pushing your code/

Like many other Version Control Systems, Git has a way to fire off custom scripts when certain important actions occur. There are two groups of these hooks: client-side and server-side. Client-side hooks are triggered by operations such as committing and merging, while server-side hooks run on network operations such as receiving pushed commits. You can use these hooks for all sorts of reasons.

With git hooks, you can make these actions automatically.

While husky is a tool to make Git hooks easier to use. To use it is very easy

First you install it as a development dependency with npm:

npm install husky --save-dev

OR yarn:

yarn add husky -D

Then in your package.json , add:

{
  "husky": {
    "hooks": {
      "pre-commit": "yarn lint",
      "pre-push": "yarn test",
      "...": "..."
    }
  }
}

In the example, we added 2 hooks, pre-commit and pre-push, they are meant what they named.

  • pre-commit means, every time you run git commit, it will run yarn lint first, and commit the code if yarn lint passes without error.
  • pre-push run command yarn test when you run git push
  • yarn lint and yarn test are commands that you define in your scripts in package.json. normally those commands that you runs manually, like yarn start or yarn dev, etc. you can add any command you want and run the, in the hooks.

Pretty straight forward and easy :)

Use document.execCommand to set value in editable field and trigger events

NOTE: This document.execCommand api has been marked as Obsolete. However, given the situation that new API is still under construction, so it’s still safe to use it for now and maybe for next few years.

To set value in editable filed like input, textarea with javascript is a common requirement in browser extension or other script development. Normally you just need to do something like document.querySelector('input').value="text you want to set" to get the job done easily and quickly.

But life is not always so easy. Actually most of the time you need to do more in browser extension development. The input fileds always bond many events like beforeinput, input,change, or even focus, active. If you just set the value by javascript, you will also need to trigger these events manually in next steps.

And before that you will need to find out what events you need to trigger. It gonna take you some time.

With this document.execCoomand, you can do it easily.

The syntax is like this:

document.execCommand(aCommandName, aShowDefaultUI, aValueArgument)

There is a insertText you can use to set value.

Inserts the given plain text at the insertion point (deletes selection).

so to insert text in to a field, you just, focus the field -> select the field -> execute the command, like so:

const element = document.querySelector("#target")
element.focus()
element.select()
document.execCommand("insertText", false, "text you want to set")

The best of this API is that, it imitates user input event, make it like human being activity, trigger all bond events on the filed.

This API is very powerful, there are a bunch of commands you can use to make you life easier.

You can read it’s doc on MDN to get more details: https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand

How to trigger click event in Gmail

If you want to hack Gmail UI, to build web extension or any other similar tool that works on top of Gmail, you always want or need to trigger some DOM events in Gmail UI, like you want to click on some buttons/icons, to send out email, to make the compose window pop out, etc.

You can’t do it by simply use click function, either by Vanilla JS or jQuery, either click or trigger function can not achieve your goal.

You need to do this by using Document.createEvent().

Take click for example, you want to click an icon:

  const mouseDown = document.createEvent('MouseEvents');
  mouseDown.initEvent('mousedown', true, false);
  icon.dispatchEvent(mouseDown);

  const mouseUp = document.createEvent('MouseEvents');
  mouseUp.initEvent('mouseup', true, false);
  icon.dispatchEvent(mouseUp);

You may want to make it as a function so that you can use it click any element.

Boost your Frontend development speed in China

Waiting for something is wasting time, especially when development, you always need to wait for compiling, wait for install dependencies…

And if you are in China, this waiting time will be much longer because of some well known reason.

Here are some changes that will save you some time in China if you are doing frontend development.

Ruby and Rails

change your gem source to China mirror, source: https://ruby-china.org/

gem source -a https://gems.ruby-china.com

npm

change your npm source to China mirror, source , source: https://developer.aliyun.com/mirror/NPM

npm config set registry https://registry.npm.taobao.org

or you can also install a cnpm, use cnpm rather than npm, to avoid change the source url permanently.

$ npm install -g cnpm --registry=https://registry.npm.taobao.org

yarn

Same as npm.

yarn config set registry https://registry.npm.taobao.org --global

there is no cyarn though

ubuntu

change sourcelist, check this post

homebrew

change homebrew core source and repo to USTC (University of Science and Technology of China) Mirror.

  • change brew.git:

     cd "$(brew --repo)"
     git remote set-url origin https://mirrors.ustc.edu.cn/brew.git
    
  • change homebrew-core.git

     cd "$(brew --repo)/Library/Taps/homebrew/homebrew-core"
     git remote set-url origin https://mirrors.ustc.edu.cn/homebrew-core.git
    
  • change homebrew bottles source

    for bash user

     echo 'export HOMEBREW_BOTTLE_DOMAIN=https://mirrors.ustc.edu.cn/homebrew-bottles' >> ~/.bash_profile
     source ~/.bash_profile
    

    for zsh user

     echo 'export HOMEBREW_BOTTLE_DOMAIN=https://mirrors.ustc.edu.cn/homebrew-bottles' >> ~/.zshrc
     source ~/.zshrc
    

RIP, Kobe Bryant

RIP

RIP, Kobe Bryant

2019 nCoV

It’s 23th Jan already.

2019-nCoV virus is raging in China and some other countries, and also lunar new year tomorrow.

Just like 17 years ago, SARS everywhere. Back then I was a senior middle school student. Sat in the classroom every day, the teachers tried sterilization by boiling vinegar in the classroom.

Luckily it’s spring soon, SARS gone quietly just like how it came. Hundreds of people died, lots of them were doctors and nurses. Feel so sad about them.

Then in 2009, there was H1N1. I was at university. I only saw the news on TV and the internet. Weird thing is, in my memory, it was not as bad as in 2003. I was busying getting prepared for job, nothing different. But I just found out today on the internet, about 648 people died in China mainland, while it was 349 in 2003 SARS. Kind of shock news to me.

And now, more than 600 people in China mainland got this virus, 17 of them dead. Heard from some news there would be more soon since Wuhan is a big city and many people who work there will go back to their own town to celebrate the lunar new year.

In the meantime in the US, CDC says about 6600 died because of the flu.

And in Australia, the fire has burnt for months and it’s still burning.

So many disasters this year. I just wish everything will be OK for everyone and no more disaster to every country and every human being.

how to keep preview file in VS Code quickly

You are a VS Code master, you barely use mouse when coding.

You want to edit a file A in your project.

You open A via hotkey, CMD+Shif+R (yes, I came from eclipse).

Before you editing A, you want to check some reference in another file B.

You open B with same hotkey, you got your information.

Then you want to go back to A to make your editing.

Where is my file A? That one with 1000 rows of code, it was there just before.

Alright I can just open it again, CMD SHIFT R, yes, it comes back.

WTF, Why is B gone?

This happens a lot before to me, I have to double click the file in the project file list to keep it open.

It’s because VS Code thinks that you just want to preview the file when you single click the file or open it with hotkey.

But it’s really annoying that you want to open multiple files in editor and keep them open.

So here is a quicky way to do this:

Press a CMD + S (Ctrl+S on Windows, that’s hotkey for save ) once you open the file. You will notice that the file name font in tab becomes regular from italic.

Change Ubuntu 18.04 update source to mirror site in China

To use ubuntu is not a easy thing, and if you are in China, it’s even more difficult. Once you want to update your ubuntu. you’d find it’s very slow. Because of some well known reason.

So it’s better to change the update source to some mirror site in China.

Here are several famous mirror sites. What you need todo is pick one from below and edit etc/apt/sources.list, replace the content in this file.

Better backup you etc/apt/sources.list before you do this

163 (netease)

source:http://mirrors.163.com/

deb http://mirrors.163.com/ubuntu/ bionic main restricted universe multiverse
deb http://mirrors.163.com/ubuntu/ bionic-security main restricted universe multiverse
deb http://mirrors.163.com/ubuntu/ bionic-updates main restricted universe multiverse
deb http://mirrors.163.com/ubuntu/ bionic-proposed main restricted universe multiverse
deb http://mirrors.163.com/ubuntu/ bionic-backports main restricted universe multiverse
deb-src http://mirrors.163.com/ubuntu/ bionic main restricted universe multiverse
deb-src http://mirrors.163.com/ubuntu/ bionic-security main restricted universe multiverse
deb-src http://mirrors.163.com/ubuntu/ bionic-updates main restricted universe multiverse
deb-src http://mirrors.163.com/ubuntu/ bionic-proposed main restricted universe multiverse
deb-src http://mirrors.163.com/ubuntu/ bionic-backports main restricted universe multiverse

alibaba (aliyun)

source:https://opsx.alibaba.com/mirror

deb http://mirrors.aliyun.com/ubuntu/ bionic main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ bionic-security main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ bionic-updates main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ bionic-proposed main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ bionic-backports main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ bionic main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ bionic-security main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ bionic-updates main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ bionic-proposed main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ bionic-backports main restricted universe multiverse

And here are also two Chinese university mirror, use them only if you are in Chinese university.

tsinghua university

deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ bionic main restricted universe multiverse
deb-src https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ bionic main restricted universe multiverse
deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ bionic-updates main restricted universe multiverse
deb-src https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ bionic-updates main restricted universe multiverse
deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ bionic-backports main restricted universe multiverse
deb-src https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ bionic-backports main restricted universe multiverse
deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ bionic-security main restricted universe multiverse
deb-src https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ bionic-security main restricted universe multiverse
deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ bionic-proposed main restricted universe multiverse
deb-src https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ bionic-proposed main restricted universe multiverse

ustc (university of science and technology of China)

deb https://mirrors.ustc.edu.cn/ubuntu/ bionic main restricted universe multiverse
deb-src https://mirrors.ustc.edu.cn/ubuntu/ bionic main restricted universe multiverse
deb https://mirrors.ustc.edu.cn/ubuntu/ bionic-updates main restricted universe multiverse
deb-src https://mirrors.ustc.edu.cn/ubuntu/ bionic-updates main restricted universe multiverse
deb https://mirrors.ustc.edu.cn/ubuntu/ bionic-backports main restricted universe multiverse
deb-src https://mirrors.ustc.edu.cn/ubuntu/ bionic-backports main restricted universe multiverse
deb https://mirrors.ustc.edu.cn/ubuntu/ bionic-security main restricted universe multiverse
deb-src https://mirrors.ustc.edu.cn/ubuntu/ bionic-security main restricted universe multiverse
deb https://mirrors.ustc.edu.cn/ubuntu/ bionic-proposed main restricted universe multiverse
deb-src https://mirrors.ustc.edu.cn/ubuntu/ bionic-proposed main restricted universe multiverse

Enjoy:)

Disable Web Search Result in Windows Search 2019

TL;DR: download this windows reg file and double click to import it. OR

  • copy the code from below
  • open you favourite text editor, or just use notepad
  • paste the code into it
  • save the file with .reg extension
  • double click the file
Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows Search ]
"ConnectedSearchUseWebOverMeteredConnections"=dword:00000000
"AllowCortana"=dword:00000000
"DisableWebSearch "=dword:00000001
"ConnectedSearchUseWeb"=dword:00000000

[HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Search]
"CortanaConsent"=dword:00000000
"BingSearchEnabled"=dword:00000000
"AllowSearchToUseLocation"=dword:00000000

Windows is promoting it’s Cortana and Bing search for a long time. One of the most annoying thing is that it’s showing web search content when you search in start menu.

So you press Windows button, type some keywords, all you want to do is just access your installed app or file quickly, but then you saw some shitty stuff in the result list.

Yes, it’s showing web search content and even some so called search suggesttion. it’s based on your keywords and some trends on the web, since you are searching how to disable this, I know that you also think it’s totally garbage.

In the beginning, Windows gave us an option in the search menu to turn this off. But then Windows known that most of the users hated it, so it just removed this option…

I have to use group policy, regeditor to disable it, and have to search for this every time when it updates.

To do it step by step is a bit complicated and it’s totally a waste of time. So I just create this reg file so that anyone who want to do this can do it by one click.

Comment for these reg code in case someone doubt it:


"ConnectedSearchUseWebOverMeteredConnections"=dword:00000000 // _disable web search use mobile connection

"AllowCortana"=dword:00000000// disable Cortana

"DisableWebSearch "=dword:00000001 // disable web search

"ConnectedSearchUseWeb"=dword:00000000 // disabled web searech connection

"CortanaConsent"=dword:00000000 // disable Cortana

"BingSearchEnabled"=dword:00000000 // disable bing search in start menu

"AllowSearchToUseLocation"=dword:00000000 // disable search feature access your location


Enjoy :)

MySQL: Sort Number in String Format

TL;DR: use key_name * 1; like

 select id, name, age from users order by salary * 1

Well, it’s better to store number data in number format in the database. But there is always accident, sometimes you or your colleague just stored some number into database with string format, of cause with some reason.

And one day you need to get data from that table and sort the result by that string-number column. Then you found something is not right.

If you run command like this:

select "1000" > "2"

you will find that the result is 0. it means, 100 < 2. that’s because mysql just compare these 2 values in as string. thus 2 > 1.

There are several work around to make this works, like use conv(). So write your sql like this:

select * from users order by conv(`salary`, 10, 10)

conv(original_value, from_base, to_base) is a mysql function, to convert a value from a base to another base, like you can also convert a numeric base system 2 to numeric base system 10.

But there is another shorter and cooler way to do this. that’s mul the value by 1. Like so:

select * from users order by salary * 1

Work like a charm.

Need to notice that if the value is too large, the result will be in Scientific notation like 1e17.

-EOF-

Chrome team just released several new official themes

I never use Chrome theme before, not a fan of customized theme because most of them are too stylish for me.

But Chrome team just released sever official themes days ago, they are clean and fresh, most of them seem for programmers. Like Oceanic, High Contrast Colorful.

You can get them from here:  https://chrome.google.com/webstore/category/collection/chrome_themes

How to block HTTPS websites on Router with Merlin

Merlin is a very powerful Router OS.

The best feature I like is its plugin system. there you can install many third-party apps like Adblock, web shell, AppleDNS. Most of the great apps are already in its built-insoftware center you can just install them with 1 click.

It also has a `Firewall`,  here you can add some rules to let the router block some URL or hosts or even IP that you don't want the users access.  

But as it says, it has some limitations:

So basically, since almost all websites are with HTTPS now, this Firewall has actually been useless now.

Of cause, since it's a mini Linux system, you can log in to it in shell and edit  hosts, but it's not that convenient to do things with the shell. 

Here is a killer app, it's been taken down because of Chinese policy, it's called shad0w20cks(you know it). 

In it's DNS Settings, there is a textarea called customize dnsmayou can just add your hosts like rules in it. like if you want to block baidu.com and weibo.com:

address=/baidu.com/127.0.0.1

address=/weibo.com/127.0.0.1

And then save.

works like a charm :D

End.

How to remove experimentalDecorators warning in VSCode

Problem

Working on a Vue project with VSCode as code editor. Using typescript in the Vue component.

While VSCode keeps warning this message on the declaration of Component class name. Which is very annoying.

Experimental support for decorators is a feature that is subject to change in a future release. Set the ‘experimentalDecorators’ option to remove this warning.

Tried to search a bit, in the VSCode github, they tell you to set experimentalDecorators to true in VSCode settings, and restart, however it's not working.

Solution

you need to modify the typescript configuration. In tsconfig.json file (if you don't have one, create it in your project's root folder). Add this:

{
    "compilerOptions": {
        "experimentalDecorators": true,
        "allowJs": true
    }
}

Both experimentalDecorators and allowJs needs to be set to true

And then restart VSCode.

Done.

zsh 主题 powerlevel9k 安装配置记录


zsh with powerlevel9k theme

安装:

git clone https://github.com/bhilburn/powerlevel9k.git ~/.oh-my-zsh/custom/themes/powerlevel9k

启用和配置

编辑 `~/.zshrc`

  • 启用

ZSH_THEME="powerlevel9k/powerlevel9k"

  • 改变配置

POWERLEVEL9K_LEFT_PROMPT_ELEMENTS=(dir vcs) #左侧显示全路径和Git状态

POWERLEVEL9K_RIGHT_PROMPT_ELEMENTS=(time ram) #右侧显示时间和内存

我本人需要的就这些,显示结果如题图。更多详细配置见:https://github.com/bhilburn/powerlevel9k

遇到乱码在iterm2的配置里面修改字体即可。

Github中国加速hosts列表

因为众所周知的原因,github对很多中国用户来说有些慢。特别在clone的时候。

可以通过修改hosts来解决。最新的hosts列表如下:

# GitHub Start  updated 15-1-2019
192.30.253.112 github.com
192.30.253.118 gist.github.com
151.101.112.133 assets-cdn.github.com
151.101.184.133 raw.githubusercontent.com
151.101.112.133 gist.githubusercontent.com
151.101.184.133 cloud.githubusercontent.com
151.101.112.133 camo.githubusercontent.com
151.101.112.133 avatars0.githubusercontent.com
151.101.112.133 avatars1.githubusercontent.com
151.101.184.133 avatars2.githubusercontent.com
151.101.12.133 avatars3.githubusercontent.com
151.101.12.133 avatars4.githubusercontent.com
151.101.184.133 avatars5.githubusercontent.com
151.101.184.133 avatars6.githubusercontent.com
151.101.184.133 avatars7.githubusercontent.com
151.101.12.133 avatars8.githubusercontent.com
# GitHub End

iTerm2 + zsh + oh my zsh 安装和配置


https://cdn-images-1.medium.com/max/1600/1*QCDLBTPMt3S7G0JOQbD68A.png

OSX的默认终端terminal功能比较基础,对于普通用户来说不是非常友好,界面也丑丑的。以上是使用iterm2 + zsh + oh my zsh 之后的效果。

除了界面很好看而外,还能实现诸如显示当前路径、系统资源占用、git状态等信息。且拥有丰富的可定制化选项,让你可以打造自己的终端。

接下来就来一步步定制自己的终端吧。

安装 Homebrew

打开终端,粘贴如下代码, 这将在你的机器上安装Homebrew,这是一个包管理工具。类似ubuntu里面的 apt.

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

安装 iTerm2

这是用来替代terminal的工具,既可以去官网下载:https://www.iterm2.com/downloads.html

也可以利用上面安装好的 Homebrew 直接安装:

brew cask install iterm2

安装 zsh

还是直接用 homebrew 来安装:

brew install zsh

安装 oh-my-zsh

如果不安装 oh-my-zsh的话,zsh会比较难用。OMZ 是一个开源的 zsh 配置管理工具,拥有很多丰富的功能、扩展和皮肤来让定制你的zsh。安装代码如下

sh -c "$(curl -fsSL https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/master/tools/install.sh)"

自定义皮肤:

网上有很多的自定义皮肤可以供下载使用。个人比较喜欢现在比较流行的 Material 风格,无论是 vscode 还是其他编辑器,均有这个风格的皮肤,非常清新。预览图如下:


https://github.com/MartinSeeler/iterm2-material-design/blob/master/img/screen-mock-1.jpg

1.下载皮肤,在终端中粘贴以下代码:

$ cd Downloads
$ curl -O https://raw.githubusercontent.com/MartinSeeler/iterm2-material-design/master/material-design-colors.itermcolors

2. 打开 iTerm2, 然后到设置(preferences)—— 用户(profiles)—— 颜色(colors)

3. 点击底部的 预设颜色... (Color Presets...)

4. 点击导入,然后找到下载文件夹里面刚才下载的扩展名为itermcolors的文件

5. 再从下拉菜单中选择刚导入的皮肤文件。


加载皮肤配置

管理扩展

oh-my-zsh 内绑定了不少扩展,这里是列表:https://github.com/robbyrussell/oh-my-zsh/wiki/Plugins

绝大多数的扩展都未默认启用,若你想启用某些扩展,需要修改其配置文件。

在 iterm2 中输入以下代码来编辑其配置文件:

nano ~/.zshrc

在文件中找到如下代码:

# Add wisely, as too many plugins slow down shell startup.
plugins=(
  git
)

这里就是配置扩展的地方,可以看到其默认启动了git扩展。要添加新扩展只要在括号里加名字即可,要注意的是,扩展越多,终端启动和运行就越慢,所以按需添加,比如我加入python常用工具pip:

plugins=(
  git
  pip
)

这样就差不多配置好了。更多配置见这里:https://github.com/robbyrussell/oh-my-zsh/wiki

Git: 删除本地所有分支并保留其中一个

本地分支多了想删掉一些。(下面所有的命令中运行时均需要把 BRANCH_NAME 换成自己要操作的分支的名字)

常用的命令是

git branch -D `BRANCH_NAME`

可是这样只能一个个删除。批量删除并保留一个分支,比如 master 分支的命令可以用下面这条命令:

git branch | grep -v "BRANCH_NAME" | xargs git branch -D 

如果你要经常这么做的话,还可以给这条命令添加个短名:

alias gdbm="git branch | grep -v "BRANCH_NAME" | xargs git branch -D"

如果要保留多个分支,可以在足命令中添加多个分支的名字:master\|develop\|test_branch。

上面的命令就变成:

git branch | grep -v "master\|develop\|test_branch" | xargs git branch -D 

I won't reinstall my server again

So I reinstalled my server again.

lost all data.

won't do this again