书写技术成长之路

Linux 添加用户并赋予sudo权限

第一步 添加用户

sudo adduser test-user

第二步 为新用户设置密码

sudo passwd test-user

第三步 将新用户加入wheel用户组

sudo usermod -aG wheel test-user

第四步 切换到新用户并测试sudo

su - test-user

sudo ls -al /root

如果成功展示,就说明新用户已经加入sudoers了

第五步 运行sudo命令不必输入密码

sudo visudo

在最后一行添加 test-user ALL=(ALL) NOPASSWD: ALL

参考地址

https://www.tecmint.com/run-sudo-command-without-password-linux/

Centos用Firewalld开启端口号

Firewalld可以用来开启一个端口号,比如开启9000端口

第一步 安装firewalld

yum install firewalld

sudo systemctl enable firewalld

sudo systemctl start firewalld

第二步 可以开启端口号了

开启端口号并永久保存 firewall-cmd --permanent --add-port=9200/tcp

重新加载端口信息 firewall-cmd --reload

显示所有已开启的端口号 firewall-cmd --list-ports

参考地址
  1. https://serverfault.com/questions/710076/centos-7-firewall-cmd-not-found

  2. https://www.rootusers.com/how-to-open-a-port-in-centos-7-with-firewalld/

Javascript常用代码片段

生成随机数

Math.random().toString(36).substring(7);

获取URL中的参数

function getUrlParameter(name) {
    name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
    var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
    var results = regex.exec(location.search);
    return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};

Python 未指定编码导致的问题

# VarArgs parameters - 变长参数
# Sometimes you might want to define a function that can take any number of parameters.
# variable number of arguments, this can be achieved by using the stars

def total(a=5, *numbers, **phonebook):
    print('a', a)

    # iterate through all the items in tuple
    for single_item in numbers:
        print('signle_item', single_item)

    # iterate through all the items in dictionary
    for first_part, second_part in phonebook.items():
        print(first_part, second_part)

print(total(10, 1, 2, 3, Jack=1123, John=2231, Inge=1560))

程序中含有中文字符,运行程序的时候直接报这个错误

SyntaxError: Non-ASCII character '\xe5' in file function_varargs.py on line 1, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details

上网查了下是由于编码问题导致的,需要在文件开头声明编码类型 # -*- coding: utf-8 -*-

也就是这样

# -*- coding: utf-8 -*-
# VarArgs parameters - 变长参数
# Sometimes you might want to define a function that can take any number of parameters.
# variable number of arguments, this can be achieved by using the stars

def total(a=5, *numbers, **phonebook):
    print('a', a)

    # iterate through all the items in tuple
    for single_item in numbers:
        print('signle_item', single_item)

    # iterate through all the items in dictionary
    for first_part, second_part in phonebook.items():
        print(first_part, second_part)

print(total(10, 1, 2, 3, Jack=1123, John=2231, Inge=1560))

array_combine 函数的误区

情景是这样的,需要记录用户的身份证和姓名信息,前端以表单的方式提交过来

前端提交的数据格式

$id_cards[] = '3306821978072033829';
$id_cards[] = '371581199202123681';

$names[] = '小李';
$names[] = '小王';

后端接收到的数据是这样处理的

$names = ['小李', '小王'];
$id_cards = ['3306821978072033829', '371581199202123681'];

$inputs = array_combine($id_cards, $names);

foreach ($inputs as $key => $value) {
        $info['id_card'] = $key;
        $info['name'] = $value;
        $result[] = $info;
}

json_encode($result);

发现最后输出结果是这样的

{
    "id_card": 3306821978072033100,
    "name": "小李"
},
{
    "id_card": 371581199202123100,
    "name": "小王"
}

怎么后面变成100了呢?不细心看还真发觉不出来这个bug。 通过调试发现,数组$id_cards全是数字,PHP就把它当成整型来处理,这时候array_combine是用身份证号作为数组的键,然后本来以为$id_cards 中的元素是字符串,在用array_combine的时候就被隐式转换为整型了,这就可能会发生超出INT的最大值而导致意想不到的结果。

最后的解决方案就是为$id_cards的每个元素添加个字符串前缀, 然后再用array_combine

array_walk($id_cards, function(&$val) {
    $val = "E".$val;
    return $val;
});

Centos更改时区后时间仍然不一致

CentOS系统时间与现在时间相差8小时解决方法

产生原因:CentOS 默认 BIOS 时间是 UTC 时间和系统时间不一致

# 第一步 vim /etc/sysconfig/clock
ZONE="Asia/Shanghai"

# 设置为 false ,硬件时钟不和 utc 时间一致
UTC=false            
ARC=false

# 第二步 
# 设置系统时区为上海 
ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime 

# 对准时间,需要先安装ntp服务器然后通过公网 NTP 服务器校准时间
yum install ntp            
ntpdate pool.ntp.org  

# hwclock 把准确的时间写入 BIOS 
hwclock --systohc    

参考 https://my.oschina.net/moooofly/blog/295847

Mac上多版本PHP

  1. 通过以下命令安装homebrew /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
  2. 通过 homebrew 安装 php56 brew install php56
  3. 为了安装php7, 需要先把php56的链接去掉 brew unlink php56
  4. 再安装 php71 brew install php71
  5. 记住不同版本的PHP扩展也要分别安装,如在php56上要使用xdebug,需要安装php56-xdebug,如果要在php7上使用,也要安装php71-xdebug
#!/bin/bash
# 切换PHP版本
# usage: ./switch_php.sh php56

if [ "$#" -ne 1 ]; then
    echo "请传入参数";
    exit 1;
fi

if [ $1 == "php56" ]
then
    brew unlink php71 && brew link php56
    rm /usr/local/bin/php
    ln -s /usr/local/Cellar/php56/5.6.29_5/bin/php  /usr/local/bin/php
    brew services stop php71 && brew services start php56
else
    brew unlink php56 && brew link php71
    rm /usr/local/bin/php
    ln -s /usr/local/Cellar/php71/7.1.3_15/bin/php /usr/local/bin/php
    brew services stop php56 && brew services start php71
fi

echo "已成功切换到$1版本";

Nginx gzip相关配置

gzip  on;                   # 开启gzip压缩
gzip_comp_level 5;          # 压缩级别(1-9) 越大压缩率越高,设置为5是在压缩率和CPU之间取得平衡
gzip_min_length 1100;       # 大于这个值的才会启用压缩,如果文件太小,则gzip压缩的结果适得其反
gzip_proxied any;           # 通过代理访问的也照样启用
gzip_types text/plain text/css application/json application/javascript application/x-javascript text/xml application/xml application/xml+rss text/javascript application/vnd.ms-fontobject application/x-font-ttf font/opentype  image/svg+xml image/x-icon;     # 压缩支持的类型

参考地址

  1. https://mattstauffer.co/blog/enabling-gzip-on-nginx-servers-including-laravel-forge
  2. https://varvy.com/pagespeed/enable-compression.html
  3. http://nginx.org/en/docs/http/ngx_http_gzip_module.html#gzip_buffers
  4. https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/optimize-encoding-and-transfer

PHP数组在指定位置处插入元素

<?php

/**
 *
 * array_splice函数是删除数组中的一部分并返回
 * 这里用它来截取要插入的元素的前面的元素,这样就可以获得要插入元素前面的数组了
 * 这时候$arr也被截取为两部分,前半部分是待插入元素前面的数组,后半部分是待插入元素后面的数组
 * 然后利用array_merge就可以实现在任意指定位置插入元素了
 */
function insert_to_array($arr, $position, $element)
{
    $first_array = array_splice($arr, 0, $position);
    $result = array_merge($first_array, $element, $arr);
    return $result;
}

$arr = ['第1条' => 'aaa', '第3条' => 'ccc', '第4条' => 'ddd'];
$insert_arr = ['第2条' => 'bbb'];
$result_arr = insert_to_array($arr, 1, $insert_arr);
print_r($result_arr);