cat】 显示文件内容【linux】


显示文件内容

cat /path/to/foo

显示文件内容带行号

cat -n /path/to/foo

显示带有行号的内容(不包括空行)

cat -b /path/to/foo

aria2c】 免费轻量级命令行下载工具【linux】


下载一个文件

网址可以是http(s)、ftp、.torrent文件,甚至是磁力链接。

aria2c

阻止下载.torrent文件

aria2c --follow-torrent=mem

一次下载1个文件 (-j)

继续(-c)任何部分下载(断点续传)

下载到指定的目录(-d)

从文件中读取URL (-i)

aria2c -j 1 -c -d ~/Downloads -i /path/to/file

chmod】 改变一个文件或目录的模式【linux】


所有人增加执行权限 (myscript.sh)

chmod a+x myscript.sh

设置用户为读/写/执行,组/全局为只读(myscript.sh),符号模式

chmod u=rwx, go=r myscript.sh

从user/group/global(myscript.sh)中删除写入权限,符号模式

chmod a-w myscript.sh

移除user/group/global(myscript.sh)的读/写/执行权限,符号模式

chmod = myscript.sh

设置用户为读/写和组/全局读(myscript.sh),八进制记号

chmod 644 myscript.sh

设置用户为读/写/执行,组/全局为读/执行权限(myscript.sh),八进制记数法

chmod 755 myscript.sh

设置用户/组/全局为读/写权限(myscript.sh),八进制记数法

chmod 666 myscript.sh

角色

u - 用户 (文件的所有者)

g - 组 (文件组的成员)

o - 全局 (所有非所有者和非组员的用户)

a - 所有 (上述所有3个角色)

数字表示法

7 - 完全 (rwx)

6 - 读写 (rw-)

5 - 读+执行 (r-x)

4 - 只读 (r--)

3 - 写+执行 (-wx)

2 - 只写 (-w-)

1 - 只执行 (--x)

0 - 无 (---)

apt-cache】 查询apt的二进制软件包缓存文件【linux】


搜索apt软件包:

apt-cache search "whatever"

显示包记录

apt-cache show pkg(s)

显示包的反向依赖项

apt-cache rdepends package_name

显示包版本、包的反向依赖项和正向依赖项

apt-cache showpkg package_name

caffeinate】 防止系统睡眠【linux】


阻止mac睡眠1小时(3600秒)

caffeinate -u -t 3600

防止mac在命令完成之前休眠

caffeinate -s command

channel】 通道【golang】


创建一个无缓冲的bool型Channel

c := make(chan int)

缓冲通道,容量为10

c := make(chan string, 10)

从Channel接收一个值,如果channel关闭或没有数据,那么ok将被置为false

x, ok = <- c

发送到一个空的通道,会永远阻塞

var c chan string

c <- "Hello, World!" 向一个Channel发送一个值

致命错误:所有goroutine都处于休眠状态-死锁!

从一个无的通道接收信息时,会永远阻塞

var c chan string

fmt.Println(<-c) 从一个Channel中接收一个值

致命的错误:所有的goroutines都处于睡眠状态--死锁!

向一个封闭的通道发送的信息会引起恐慌

var c = make(chan string, 1)

c <- "Hello, World!"

close(c)

c <- "Hello, Panic!"

恐慌:在封闭通道上发送

从一个封闭的通道接收,立即返回零值

var c = make(chan int, 2)

c <- 1

c <- 2

close(c)

for i := 0; i < 3; i++ {

    fmt.Printf("%d ", <-c)

}

1 2 0

for循环读取channel

for i := range ch { ch关闭时,for循环会自动结束

    println(i)

}

防止读取超时

select {

    case <- time.After(time.Second*2):

        println("read channel timeout")

    case i := <- ch:

        println(i)

}

防止写入超时

select {

    case <- time.After(time.Second *2):

        println("write channel timeout")

    case ch <- "hello":

        println("write ok")

}

asciiart】 使用纯文本来显示图像【linux】


figlet Cheat

一些带有颜色和其他选项的文本

用边框显示

toilet -F border Cheat

基本展示(已填充)

toilet Cheat

VACUUM】 回收已删除元组占据的存储空间【postgresql】


VACUUM [ FULL | FREEZE ] [ VERBOSE ] [ table ]

VACUUM [ FULL | FREEZE ] [ VERBOSE ] ANALYZE [ table [ (column [, ...] ) ] ]

FULL ------选择"完全"清理,这样可以恢复更多的空间, 但是花的时间更多并且在表上施加了排它锁。

FREEZE ---------选择激进的元组"冻结"。

VERBOSE --------- 为每个表打印一份详细的清理工作报告。

ANALYZE --------- 更新用于优化器的统计信息,以决定执行查询的最有效方法。

table ------- 要清理的表的名称(可以有模式修饰)。缺省时是当前数据库中的所有表。

column ---------要分析的具体的列/字段名称。缺省是所有列/字段。

ccze】 彩色日志工具【linux】


ccze使用命名管道一次为多个日志文件的尾部着色

mkfifo pipe

tail -s .5 -n 120 -f httpd_access_log httpd_error_log httpd_modsec_audit_log >pipe &

ccze < pipe

ifconfig】 显示或设置网络设备【linux】


显示适配器wlan0的网络设置

ifconfig wlan0

显示所有接口,即使关闭

ifconfig -a

启用/停用无线适配器

ifconfig wlan0 {up|down}

设置静态IP和网络掩码

ifconfig eth0 192.168.1.100 netmask 255.255.255.0

添加网关IP

route add -net 192.168.1.0 netmask 255.255.255.0 gw 192.168.1.1

imgcat】 命令行上显示图像的实用程序【linux】


需要一个兼容的终端,如iTerm2

在命令行上显示图像

imgcat filename

change】 类型转换【golang】


int -> string

i := strconv.Itoa(x)

string -> int

i,err := strconv.Atoi(x)

string -> int64

int64,err := strconv.PareInt(string,10,64)

int64 -> string

string := strconv.FormatInt(int64,10)

int64 -> int

i := int(int64)

int -> int64

int64,err := int64(xxx)

float -> string

string := strconv.FormatFloat(float32,'E',-1,32)

string := strconv.FormatFloat(float64,'E',-1,64)

'b' (-ddddp±ddd,二进制指数)

'e' (-d.dddde±dd,十进制指数)

'E' (-d.ddddE±dd,十进制指数)

'f' (-ddd.dddd,没有指数)

'g' ('e':大指数,'f':其它情况)

'G' ('E':大指数,'f':其它情况)

string -> float64/32

float,err := strconv.ParseFLoat(string,64)

float,err := strconv.ParseFLoat(string,32)

cups】 通过CUPS管理打印机【linux】


通过CUPS管理打印机:

http:localhost:631 (浏览器中)

从命令行控制打印文件

lp myfile.txt

显示打印队列

lpq

从队列中删除打印作业

lprm 545

或者

lprm -

打印日志位置

/var/log/cups

拒绝新任务

cupsreject printername

接受新任务

cupsaccept printername

asciiart】 使用纯文本来显示图像【linux】


figlet Cheat

一些带有颜色和其他选项的文本

用边框显示

toilet -F border Cheat

基本展示(已填充)

toilet Cheat

declarations】 变量声明【golang】


var foo int 普通定义

var foo int = 42 定义并初始化

var foo, bar int = 42, 1302 一次写义多个

var foo = 42 类型省略,将被推断为某个类型

foo := 42 简称,仅在func体中,省略var关键字,类型总是隐含的

const constant = "This is a constant" 常量

docker】 开源的应用容器引擎【linux】


拉取镜像

docker pull ${CONTAINER NAME}

查看本地所有镜像

docker images

查看所有正在运行的容器,加-q返回id

docker ps

查看所有容器,加-q返回id

docker ps -a

删除镜像

docker rmi ${IMAGE NAME/ID}

删除容器

docker rm ${CONTAINER NAME/ID}

将镜像保存成文件

docker save ${IMAGE NAME} > ${FILE NAME}.tar

从文件加载镜像

docker load < ${FILE NAME}.tar

运行一个以前运行过的容器

docker start ${CONTAINER NAME/ID}

停止一个正在运行的容器

docker stop ${CONTAINER NAME/ID}

显示运行容器的日志

docker logs ${CONTAINER NAME/ID}

运行一个容器

docker run...

    --name ${container name} #设置容器名称

    -p ${host port}:${container port} #映射主机和容器内的端口

    -e ${env name}=${env value} #添加环境变量

    -d #后台运行

    -v ${host folder path}:${container folder path} #将主机目录挂在到容器内

显示所有退出的容器

docker ps -f "status=exited"

显示所有容器id

docker ps -a -q

显示所有退出容器的id

docker ps -f "status=exited" -q

重启所有正在运行的容器

docker restart $(docker ps -q)

停止所有容器

docker stop $(docker ps -a -q)

删除所有容器

docker rm $(docker ps -a -q)

删除所有退出的容器

docker rm $(docker ps -f "status=exited" -q)

停止并删除所有容器

docker rm $(docker stop $(docker ps -a -q))

启动所有容器

docker start $(docker ps -a -q)

删除所有镜像

docker rmi $(docker images -a -q)

进入容器内

docker exec -it ${CONTAINER NAME/ID} /bin/bash

一个容器ping另外一个容器

docker exec -it ${CONTAINER NAME/ID} ping ${CONTAINER NAME/ID}

显示一个容器的top信息

docker top ${CONTAINER NAME/ID}

显示容器统计信息(正在运行)

docker stats

    docker stats -a #显示所有容器的统计信息(包括没有运行的)

    docker stats -a --no-stream #显示所有容器的统计信息(包括没有运行的) ,只显示一次

    docker stats --no-stream | sort -k8 -h #统计容器信息并以使用流量作为倒序

docker system

      docker system df #显示硬盘占用

      docker system events #显示容器的实时事件

      docker system info #显示系统信息

      docker system prune #清理文件

cut】 在文件中负责剪切数据用【linux】


切除第三个字段的文本或std输出,该字段以#号为界

cut -d# -f3

保留 1 到 24 之间(闭区间)的字符

cut -c -24 BALANCE.txt

保留 1 到 24(闭区间)以及 36 到 59(闭区间)之间的字符

cut -c -24,36-59 BALANCE.txt

保留 1 到 24(闭区间)、36 到 59(闭区间)和 93 到该行末尾之间的字符

cut -c -24,36-59,93- BALANCE.txt

gcc】 编译工具【linux】


编译文件

gcc file.c

使用自定义输出编译文件

gcc -o file file.c

调试符号

gcc -g

使用所有符号进行调试

gcc -ggdb3

构建64字节

gcc -m64

将目录{/usr/Include/myPersonnal/lib/}包含到 #include <....>

使用此选项,{/usr/include/myPersonnal/lib/}中的文件不会报告任何警告/错误

gcc -isystem /usr/include/myPersonnal/lib/

为windows构建GUI(Mingw)(将禁用术语/控制台)

gcc -mwindows

cleanmgr】 系统自带的自动清除临时文件、垃圾的工具【win】


cleanmgr [/d ] [/sageset:n] [/sagerun:n] [/TUNEUP:n] [/LOWDISK] [/VERYLOWDISK]

参数 说明

/d 指定要清理磁盘清理的驱动器。

  注意:/d选项不与 一起使用 。

/sageset:n 显示"磁盘设置"对话框,并创建一个注册表项来存储你选择的设置。 通过存储在注册表中的 值,可以指定要运行 n 磁盘清理的任务。 该值 n 可以是从 0 到 9999 的任何整数值。

/sagerun:n 如果使用 /sageset 选项,则运行分配给 n 值的指定任务。 将枚举计算机上的所有驱动器,并且所选配置文件针对每个驱动器运行。

/tuneup:n 为同一 运行 /sageset和 /sagerun。

/lowdisk 使用默认设置运行 。

/verylowdisk 使用默认设置运行,无用户提示。

/? 在命令提示符下显示帮助。

ascii】 ASCII值【linux】


ASCII值 控制字符

0 NUT 32 (space) 64 @ 96 、

1 SOH 33 ! 65 A 97 a

2 STX 34 " 66 B 98 b

3 ETX 35 # 67 C 99 c

4 EOT 36 $ 68 D 100 d

5 ENQ 37 % 69 E 101 e

6 ACK 38 & 70 F 102 f

7 BEL 39 , 71 G 103 g

8 BS 40 ( 72 H 104 h

9 HT 41 ) 73 I 105 i

10 LF 42 * 74 J 106 j

11 VT 43 + 75 K 107 k

12 FF 44 , 76 L 108 l

13 CR 45 - 77 M 109 m

14 SO 46 . 78 N 110 n

15 SI 47 / 79 O 111 o

16 DLE 48 0 80 P 112 p

17 DCI 49 1 81 Q 113 q

18 DC2 50 2 82 R 114 r

19 DC3 51 3 83 S 115 s

20 DC4 52 4 84 T 116 t

21 NAK 53 5 85 U 117 u

22 SYN 54 6 86 V 118 v

23 TB 55 7 87 W 119 w

24 CAN 56 8 88 X 120 x

25 EM 57 9 89 Y 121 y

26 SUB 58 : 90 Z 122 z

27 ESC 59 ; 91 [ 123 {

28 FS 60 < 92 \ 124 |

29 GS 61 = 93 ] 125 }

30 RS 62 > 94 ^ 126

31 US 63 ? 95 _ 127 DEL

scp】 通过SSH协议安全地将文件复制到远程或本地系统【linux】


格式

scp [-1246BCpqrv] [-c cipher] [-F ssh_config] [-i identity_file]

[-l limit] [-o ssh_option] [-P port] [-S program]

[[user@]host1:]file1 [...] [[user@]host2:]file2

    -1: 强制scp命令使用协议ssh1

    -2: 强制scp命令使用协议ssh2

    -4: 强制scp命令只使用IPv4寻址

    -6: 强制scp命令只使用IPv6寻址

    -B: 使用批处理模式(传输过程中不询问传输口令或短语)

    -C: 允许压缩。(将-C标志传递给ssh,从而打开压缩功能)

    -p:保留原文件的修改时间,访问时间和访问权限。

    -q: 不显示传输进度条。

    -r: 递归复制整个目录。

    -v:详细方式显示输出。scp和ssh(1)会显示出整个过程的调试信息。这些信息用于调试连接,验证和配置问题。

    -c cipher: 以cipher将数据传输进行加密,这个选项将直接传递给ssh。

    -F ssh_config: 指定一个替代的ssh配置文件,此参数直接传递给ssh。

    -i identity_file: 从指定文件中读取传输时使用的密钥文件,此参数直接传递给ssh。

    -l limit: 限定用户所能使用的带宽,以Kbit/s为单位。

    -o ssh_option: 如果习惯于使用ssh_config(5)中的参数传递方式,

    -P port:注意是大写的P, port是指定数据传输用到的端口号

    -S program: 指定加密传输时所使用的程序。此程序必须能够理解ssh(1)的选项。

复制文件到远程服务器

scp foo.txt user@example.com:remote/dir

复制远程文件到本地

scp user@example.com:remote/dir/foo.txt local/dir

cd】 改变目录【linux】


转到指定的目录

cd path/to/directory

转到当前用户的主目录

cd

跳转到当前目录的父级

cd ..

转到之前选择的目录

cd -

function】 脚本中的函数【linux】


从函数中中止整个脚本

trap "exit 1" TERM

export TOP_PID=$$

function fatal()

{

  echo "Goodbye"

  kill -s TERM $TOP_PID

}

echo "Function call will abort"

echo $(func)

echo "This will never be printed"

screen】 视窗多重复用管理程序【linux】


开始新的命名屏幕会话

screen -S session_name

从当前会话中分离

Press Ctrl+A then press d

重新恢复会话:

screen -r session_name

列出所有会话:

screen -ls

会话共享

screen -x

启动一个开始就断开的会话,会话名称为test.

所有屏幕输出都会记录到screenlog.0文件

scrreen -L -dmS test

热键

ctrl+a d (按ctrl不放,分别按a和d)

chown】 改变文件所有者【linux】


改变文件所有者

chown user file

改变文件所有者和所在组

chown user:group file

递归地更改所有者

chown -R user directory

更改所有权以匹配其他文件

chown --reference=/path/to/ref_file file

dict】 命令行下中英文翻译工具【linux】


通过执行以下操作查询所有可用词典的列表

dict -I

将 "understand "翻译成荷兰语

dict -d fd-eng-nld understand

显示可用的dict数据库

dict -D

ipconfig】 查看本机的网络信息【win】


查看本地网络配置

ipconfig /all

释放IP

ipconfig /release

重新获得IP

ipconfig /renew

nc】 netcat 网络界的瑞士军刀【linux】


安装:apt-get install netcat

nc的常用的几个参数如下所列:

-l 用于指定nc将处于侦听模式。指定该参数,则意味着nc被当作server,侦听并接受连接,而非向其它地址发起连接。

-p 暂未用到(老版本的nc可能需要在端口号前加-p参数,下面测试环境是centos6.6,nc版本是nc-1.84,未用到-p参数)

-s 指定发送数据的源IP地址,适用于多网卡机

-u 指定nc使用UDP协议,默认为TCP

-v 输出交互或出错信息,新手调试时尤为有用

-w 超时秒数,后面跟数字

-z 表示zero,表示扫描时不发送任何数据

tcp监听

nc -l -p 9999

作为客户端工具进行端口探测

-v可视化,-z扫描时不发送数据,-w超时几秒,后面跟数字

nc -vz -w 2 10.0.1.161 9999

nc -vzw 2 10.0.1.161 9998-9999

udp监听

nc -ul -p 9998

udp端口扫描

nc -vuz 10.0.1.161 1-1000

nc传输文件

nc -l -p 9995 > file # 端口接收到文件存为file

nc 10.0.0.1 9995 < file # 发送文件file到ip和端口

nc -l -p 9992 < file # 准备发送文件file到端口9992

nc 10.0.0.1 9992 > file # 连接到指定ip和端口,将接收到的内容存为file

传输目录

nc -l -p 9995 | tar xzvf - # 等待接收

tar cfz - * | nc 10.0.0.1 9995 # 把当前目录下的所有文件打包为-,然后nc发送给目标

网速测试(通过dstat等工具观察速率)

nc -l 9991 >/dev/null # 目标机上等待接收数据,但不保存(用于观察两者之间的速率)

nc 10.0.0.1 9991 < /dev/zero # 给目标主机发送无限的0

打开到主机host.example.com的TCP端口42进行连接,使用端口31337作为源端口,超时时间为5秒:

nc -p 31337 -w 5 host.example.com 42

网络克隆硬盘(非mount系统上进行)

nc -l -p 1234 | dd of=/dev/sda # 目标,监听,写入

dd if=/dev/sda | nc 10.0.0.1 1234 # 源:读取,发送

打开主机UDP端口53进行连接

nc -u host.example.com 53

打开到主机host.example.com端口42的TCP连接,使用10.1.2.3作为连接本地端的IP

nc -s 10.1.2.3 host.example.com 42

在UNIX域流套接字上创建和侦听

nc -lU /var/tmp/dsocket

连接到主机host.example.com的端口42,通过HTTP代理在10.2.3.4端口8080访问。ssh(1)也可以使用这个示例;

有关更多信息,请参阅ssh_config(5)中的ProxyCommand指令。

nc -x10.2.3.4:8080 -Xconnect host.example.com 42

同样的例子,如果代理需要,这一次使用用户名“ruser”启用代理身份验证

nc -x10.2.3.4:8080 -Xconnect -Pruser host.example.com 42

使用-s选项为测试选择源IP

nc -zv -s source_IP target_IP Port

lorca】 golang图像界面库【golang】


用于在 Go 中构建现代 HTML5 桌面应用程序. 它使用 Chrome 浏览器作为 UI 层

Github

struct】 结构【golang】


没有类,只有结构。结构可以有方法。

结构是一种类型。它也是字段的集合

定义

type Vertex struct {

    X, Y int

}

创建

var v = Vertex{1, 2}

var v = Vertex{X: 1, Y: 2} 通过使用键定义值来创建结构

var v = []Vertex{{1,2},{5,2},{5,5}} 初始化一个结构片

访问成员

v.X = 4

可以在结构上声明方法。

要在其上声明方法的结构(接收类型)位于func关键字和方法名称之间

每次方法调用时都会复制结构(!)

func (v Vertex) Abs() float64 {

    return math.Sqrt(v.X*v.X + v.Y*v.Y)

}

调用方法

v.Abs()

对于变异方法,您需要使用指向结构的指针(见下文)作为类型。这样,就不会为方法调用复制结构值。

func (v *Vertex) add(n float64) {

    v.X += n

    v.Y += n

}

匿名结构

比使用“map[string]interface{}”更便宜、更安全。

point := struct {

    X, Y int

}{1, 2}

blktrace】 块层的IO追踪机制,提供关于请求队列操作的详细信息,直到用户空间。【linux】


追踪/dev/sdb磁盘上的PC(非文件系统请求,PC)。

blkparse生成人类可读的格式化信息

blktrace /dev/sdb -a PC -o - | blkparse -i -

carthage】 用于Cocoa应用程序的依赖性管理工具(Mac OS X)【linux】


下载Cartfile中提到的所有依赖项的最新版本,并构建它们

carthage update

更新依赖项,但只为iOS构建

carthage update --platform ios

更新依赖项,但不构建任何依赖项

carthage update --no-build

下载并重建当前版本的依赖项(不更新它们)

carthage bootstrap

重建一个特定的依赖关系

carthage build dependency

interface】 接口【golang】


接口声明

type Awesomizer interface {

    Awesomize() string

}

类型Foo声明要实现接口

type Foo struct {}

相反,类型隐含地满足一个接口

如果它们实现了所有需要的方法

func (foo Foo) Awesomize() string {

    return "Awesome!"

}

clip】 将命令行工具的输出重定向到Windows剪贴板【win】


将当前目录列表的副本放入Windows剪贴板

dir | clip

将readme.txt中的文本副本放置到Windows剪贴板上

clip < readme.txt

清除Windows剪贴板中的内容

echo off | clip

使用ipconfig命令显示所有网络信息,并将内容输出到Windows剪贴板

ipconfig /all | clip

将字符串 Hello 放入 Windows 剪贴板

echo Hello | clip

cheat_readme】 关于腾图小抄【linux】


这是一个cheat.sh小抄的Go版实现 Chris Lane's cheatsheet。

微信版可以搜索小程序:腾图小抄

使用

搜索规则:上一条规则未搜索出内容,将进行下一条搜索规则

1. 关键词完全匹配
2. 关键词模糊匹配
3. 标题模糊匹配
4. 内容模糊匹配

浏览器:

1. https:scwy.net/关键词 -- 搜索所有分类关键词
2. https:scwy.net/分类/关键词 -- 搜索分类中的关键词
3. https:scwy.net/分类 -- 分类关键词列表
4. https:scwy.net/list -- 列出所有分类
5. https:scwy.net/cheat_down -- 下载小抄到本地 (功能待完成)
6. https:scwy.net/cheat_install --安装小抄到本机 (功能待完成)

例如 https:scwy.net/tar

命令行界面:

1. curl https:scwy.net/关键词 -- 搜索所有分类关键词
2. curl https:scwy.net/分类/关键词 -- 搜索分类中的关键词
3. curl https:scwy.net/分类 -- 分类关键词列表

例如:curl https:scwy.net/tar

宝藏

1. https:scwy.net/tools 众多在线工具
2. https:scwy.net/符号 大量的特殊符号和符号图片

计划

1. 正在对原有小抄进行改版。
2. 多语言处理.
3. 计划可以个人本地使用(本地数据库或者网络共享数据库)
4. 将小抄的领域扩展到非IT
5. 等待一个好的域名
6. 或许做一个头条小程序
7. 内容不断添加中

支持

欢迎大家共同建立小抄数据,支持作者继续完善。

支持作者

联系

发送信息到我的微信

网站备案

蜀ICP备2021009474号

cp】 复制文件【linux】


创建一个复制文件

cp ~/Desktop/foo.txt ~/Downloads/foo.txt

复制目录

cp -r ~/Desktop/cruise_pics/ ~/Pictures/

创建一个副本,但如果目标文件已经存在,则要求覆盖。

cp -i ~/Desktop/foo.txt ~/Documents/foo.txt

创建一个带有日期的备份文件

cp foo.txt{,."$(date +%Y%m%d-%H%M%S)"}

switch】 分支操作【golang】


switch语句

switch operatingSystem {

case "darwin":

    fmt.Println("Mac OS Hipster")

case "linux":

    fmt.Println("Linux Geek")

default:

     Windows, BSD, ...

    fmt.Println("Other")

}

与for和if一样,可以在开关值之前使用赋值语句

switch os := runtime.GOOS; os {

case "darwin": ...

}

您还可以在开关情况下进行比较

number := 42

switch {

    case number < 42:

        fmt.Println("Smaller")

    case number == 42:

        fmt.Println("Equal")

    case number > 42:

        fmt.Println("Greater")

}

cls】 清除屏幕【win】


如果 CLS 被重定向到文件、控制台或通过 FOR /F 执行,它将打印换行符 (ASCII 10)。

slices】 切片【golang】


var a []int 声明一个切片-类似于数组,但长度未指定

var a = []int {1, 2, 3, 4} 声明并初始化切片(由隐式给定的数组支持)

a := []int{1, 2, 3, 4} 直接定义

chars := []string{0:"a", 2:"c", 1: "b"} ["a", "b", "c"]

var b = a[lo:hi] 创建从索引lo到hi-1的切片(数组视图)

var b = a[1:4] 从索引1到索引3切片

var b = a[:3] 缺少低索引意味着0

var b = a[3:] 缺少高指数意味着len(a)

a = append(a,17,3) 将项目附加到切片

c := append(a,b...) 连接切片a和切片b

使用make创建一个切片

a = make([]byte, 5, 5) 第1个参数长度,第2个参数容量

a = make([]byte, 5) 容量是可选的

从数组创建切片

x := [3]string{"Лайка", "Белка", "Стрелка"}

s := x[:] a slice referencing the storage of x

select】 数据查询【sql】


SELECT[ALL|DISTINCT|DISTINCTROW|TOP]

{*|talbe.*|[table.]field1[AS alias1][,[table.]field2[AS alias2][,…]]}

FROM tableexpression[,…][IN externaldatabase]

[WHERE…]

[GROUP BY…]

[HAVING…]

[ORDER BY…]

SELECT 列名称 FROM 表名称

SELECT * FROM 表名称

Where(条件)

= 等于

<> 不等于

大于 小于

= 大于等于

<= 小于等于

BETWEEN 在某个范围内

LIKE 搜索某种模式

Distinct 查询时忽略重复值

SELECT DISTINCT 列名称 FROM 表名称

crontab】 定时任务【linux】


设置一个解析环境

SHELL=/bin/bash

crontab格式

- - - - -

| | | | |

| | | | +- 周几 (0 - 7) (一周是从0-7)

| | | +--- 月 (1 - 12)

| | +----- 日 (1 - 31)

| +------- 时 (0 - 23)

+--------- 分 (0 - 59)

示例

每5分钟运行

*/15 * * * * /home/user/command.sh

每到午夜

0 0 * * * /home/user/command.sh

每周六上午8:05

5 8 * * 6 /home/user/command.sh

iconv】 给定文件把它的内容从一种编码转换成另一种编码【linux】


将文件(iconv.src)从iso-8859-1转换为utf-8并保存为/tmp/iconv.out

iconv -f iso-8859-1 -t utf-8 iconv.src -o /tmp/iconv.out

cryptsetup】 【linux】


open encrypted partition /dev/sdb1 (reachable at /dev/mapper/backup)

cryptsetup open --type luks /dev/sdb1 backup

open encrypted partition /dev/sdb1 using a keyfile (reachable at /dev/mapper/hdd)

cryptsetup open --type luks --key-file hdd.key /dev/sdb1 hdd

close luks container at /dev/mapper/hdd

cryptsetup close hdd

PatternMatching】 【rust】


let foo = OptionalI32::AnI32(1);

match foo {

    OptionalI32::AnI32(n) => println!("it’s an i32: {}", n),

    OptionalI32::Nothing => println!("it’s nothing!"),

}

Advanced pattern matching

struct FooBar { x: i32, y: OptionalI32 }

let bar = FooBar { x: 15, y: OptionalI32::AnI32(32) };

match bar {

    FooBar { x: 0, y: OptionalI32::AnI32(0) } =>

        println!("The numbers are zero!"),

    FooBar { x: n, y: OptionalI32::AnI32(m) } if n == m =>

        println!("The numbers are the same"),

    FooBar { x: n, y: OptionalI32::AnI32(m) } =>

        println!("Different numbers: {} {}", n, m),

    FooBar { x: _, y: OptionalI32::Nothing } =>

        println!("The second number is Nothing!"),

}

cacls】 Display or modify Access Control Lists (ACLs) for files and folders.【win】


Syntax

      CACLS pathname [options]

Options:

   /T Search the pathname including all subfolders. (/TREE)

   /E Edit ACL, leave existing rights unchanged (/EDIT)

   /C Continue on access denied errors. (/CONTINUE)

   /L Work on the Symbolic Link itself versus the target (/LINK)

   /M Change ACLs of volumes mounted to a directory (/MOUNT)

   /G user:permission

        Grant access rights (/GRANT), permision can be:

          R Read

          W Write

          C Change (read/write)

          F Full control

   /R user

        Revoke specified user's access rights, only valid with /E. (/REVOKE)

   /P user:permission

        Replace access rights (/REPLACE), permission can be:

          R Read

          W Write

          C Change (read/write)

          F Full control

          N None

   /D user

        Deny access to user. (/DENY)

   /S

        Display the SDDL string for the DACL. (/SSDL)

   /S:sddl

        Replace the ACL(s) with those specified in the SDDL string

        (not valid with /E, /G, /R, /P, or /D).

   (The long /aliases in brackets are undocumented)

In all the options above "user" can be a UserName or a group (either local or global)

You can specify more than one user:permission in a single command.

Wildcards can be used to specify multiple files.

If a UserName or GroupName includes spaces then it must be surrounded with quotes e.g. "Authenticated Users"

If no options are specified CACLS will display the ACLs for the file(s)

Setting Deny permission (/D) will deny access to a user even if they also belong to a group that grants access.

Limitations

    Cacls cannot display or modify the ACL state of files locked in exclusive use.

    Cacls cannot set the following permissions: change permissions, take ownership, execute, delete use XCACLS to set any of these.

Using CACLS

    The CACLS command does not provide a /Y switch to automatically answer 'Y' to the Y/N prompt. However, you can pipe the 'Y' character into the CACLS command using ECHO, use the following syntax:

    ECHO Y| CACLS filename /g username:permission

    To edit a file you must have the "Change" ACL (or be the file's owner)

    To use the CACLS command and change an ACL requires "FULL Control"

    File "Ownership" will always override all ACL's - you always have Full Control over files that you create.

    If CACLS is used without the /E switch all existing rights on [pathname] will be replaced, any attempt to use the /E switch to change a [user:permission] that already exists will raise an error. To be sure the CACLS command will work without errors use /E /R to remove ACL rights for the user concerned, then use /E to add the desired rights.

    The /T option will only traverse subfolders below the current directory

    If no options are specified CACLS will display the current ACLs

    To display the current folder:

    CACLS .

    Display permissions for one file:

    CACLS MyFile.txt

    Display permissions for multiple files:

    CACLS *.txt

    Inherited folder permissions are displayed as:

     OI - Object inherit - This folder and files. (no inheritance to subfolders)

     CI - Container inherit - This folder and subfolders.

     IO - Inherit only - The ACE does not apply to the current file/directory

     ID - Inherited - The ACE was inherited from the parent directory's ACL.

    These can be combined as follows:

     (OI)(CI) This folder, subfolders, and files.

     (OI)(CI)(IO) Subfolders and files only.

         (CI)(IO) Subfolders only.

     (OI) (IO) Files only.

    So BUILTIN\Administrators:(OI)(CI)F means that both files and Subdirectories will inherit 'F' (Fullcontrol)

    similarly (CI)R means Directories will inherit 'R' (Read folders only = List permission)

    To actually change the inheritance of a folder/directory use iCACLS /grant or iCACLs /deny

    When cacls is applied to the current folder only there is no inheritance and so no output.

Errors when changing permissions

    If a user or group has a permission on a file or folder and you grant a second permission to the same user/group on the same folder, NTFS will sometimes produce the error message "The parameter is incorrect" To fix this (or prevent it happening) revoke the permission first /e /r and then apply a fresh grant /e /g

    No mapping between account names and security IDs was done

    This error indicates that cacls looked up the group or username given in Active Directory and didn't find anything, often this means that you need to prefix the name with a domain name ss64dom\user64 or (for a local account) the name of the machine pc64\localUser2 also check for simple typos.

Examples:

Add Read-Only permission to a single file

CACLS myfile.txt /E /G "Power Users":R

Add Full Control permission to a second group of users

CACLS myfile.txt /E /G "FinanceUsers":F

Now revoke the Read permissions from the first group

CACLS myfile.txt /E /R "Power Users"

Now give the first group Full-control:

CACLS myfile.txt /E /G "Power Users":F

Give the Finance group Full Control of a folder and all sub folders

CACLS c:\docs\work /E /T /C /G "FinanceUsers":F

comparison】 【mongo】


equals to

db.books.find({year: {$eq: 2016}})

less than

db.books.find({year: {$lt: 2010}})

less than or equal to

db.books.find({year: {$lte: 2008}})

greater than

db.books.find({year: {$gt: 2014}})

greater than or equal to

db.books.find({year: {$gte: 2008}})

not equal to

db.books.find({year: {$ne: 2008}})

value in

db.books.find({year: {$in: [2008, 2016]}})

value not in

db.books.find({year: {$nin: [2008, 2016]}})

bcdboot】 Set up a system partition, repair the boot environment located on the system partition【win】


Syntax

      BCDBOOT source [/l locale] [/s volume-letter [/f firmware]] [/v]

         [/vbcd] [/m [{OS_Loader_GUID}]] [/addlast] [/p] [/bcdclean [full]] [/c]

Options

   source The location of the Windows directory to use as the source for

           copying boot-environment files.

   /l The locale to use when initialising the BCD store. default = US English.

   /s Optional. Specifies the volume letter of the system partition.

           This option should not be used in typical deployment scenarios.

           Use this setting to specify a system partition when you are configuring a drive that will

           be booted on another computer, such as a USB flash drive or a secondary hard drive.

           The default is the system partition identified by the firmware.

   /v Enable verbose mode.

   /vbcd Enable BCD Logging.

   /m If an OS_Loader_GUID is specified, merge the given loader object within

           the system template to produce a bootable entry.

           Otherwise, by default, merge only global objects.

   /d Preserve the existing default Windows Boot entry.

   /f Used with /S, specifies the firmware type of the target system partition

           Options for firmware are 'UEFI', 'BIOS', or 'ALL'

           If you specify 'ALL', BCDBoot will create both the \Boot and the \Efi\Microsoft\Boot

           directories, and will copy all required boot-environment files for BIOS and UEFI.

  /addlast Specifies that the Windows Boot Manager firmware entry should be added last.

           The default behavior is to add it first. Cannot be used with /p.

  /bcdclean Clean the BCD Store. By default, simply removes any duplicate entries in

           the BCD. Can be followed by 'full'. In this case, each entry is scanned

           If the corresponding device for that entry does not exist, the entry is deleted.

   /p Specifies that the existing Windows Boot Manager firmware entry position should be

           preserved in the UEFI boot order. If the entry does not exist, a new entry is

           added in the first position. Cannot be used with /addlast.

           By default, during an upgrade BCDBoot moves the Windows Boot Manager to be

           the first entry in the UEFI boot order.

   /c Specifies that any existing BCD elements should not be migrated.

           By default, during an upgrade, BCD elements such as debugsettings or flightsigning are preserved.

Initialize the system partition by using BCD files from the C:\Windows folder

bcdboot C:\Windows

Set the default BCD locale to Japanese, and copy BCD (Boot Configuration Data) files to drive S

bcdboot C:\Windows /l ja-jp /s S:

Merge the OS loader in the current BCD store identified with the given GUID in the new BCD store

bcdboot c:\windows /m {d58d10c6-df53-11dc-878f-00064f4f4e08}

rclone】 similar to rsync【linux】


rclone is a command line tool, similar to rsync, with the difference that

it can sync, move, copy, and in general do other file operations on cloud services

Config rclone

rclone config

Lists a re

rclone ls remote:path

Copy /local/path to the remote

rclone copy /local/path remote:path

Sync /local/path to the remote

rclone sync /local/path remote:path

Server side Copy

rclone copy s3:oldbucket s3:newbucket

svcs】 List information about running services (Solaris)【linux】


List all running services:

svcs

List services that are not running:

svcs -vx

List information about a service:

svcs apache

Show location of service log file:

svcs -L apache

Display end of a service log file:

tail $(svcs -L apache)

docker】 【linux】


Start docker daemon

docker -d

start a container with an interactive shell

docker run -ti /bin/bash

"shell" into a running container (docker-1.3+)

docker exec -ti bash

inspect a running container

docker inspect (or )

Get the process ID for a container

Source: https:github.com/jpetazzo/nsenter

docker inspect --format {{.State.Pid}}

List the current mounted volumes for a container (and pretty print)

Source:

http:nathanleclaire.com/blog/2014/07/12/10-docker-tips-and-tricks-that-will-make-you-sing-a-whale-song-of-joy/

docker inspect --format='{{json .Volumes}}' | python -mjson.tool

Copy files/folders between a container and your host

docker cp foo.txt mycontainer:/foo.txt

list currently running containers

docker ps

list all containers

docker ps -a

list all images

docker images

ccze】 【linux】


ccze usage with named pipe for coloring tail of multiple logfiles at once:

mkfifo pipe

tail -s .5 -n 120 -f httpd_access_log httpd_error_log httpd_modsec_audit_log >pipe &

ccze < pipe

libreoffice】 【linux】


Convert documents to PDF

libreoffice --headless --convert-to pdf *.pptx

Save them to a different directory?

libreoffice --headless --convert-to pdf *.docx --outdir ~/docs/

Convert files nested inside folders?

This uses sharkdp/fd, you could use GNU find, xargs etc.

fd -e doc -e docx -x libreoffice --headless --convert-to pdf --outdir {} {}

DataStructures】 【scala】


sole member of the Unit type (like C/Java void).

() (empty parens)

tuple literal

This example would be a Tuple3

(1,2,3)

tuple sugar

This example would be a Tuple2

(1 -> 2) same as

(1, 2)

destructuring bind: tuple unpacking via pattern matching.

var (x,y,z) = (1,2,3)

hidden error: each assigned to the entire tuple.

BAD

var x,y,z = (1,2,3)

list (immutable).

var xs = List(1,2,3)

paren indexing. (slides)

more on it: https:www.slideshare.net/Odersky/fosdem-2009-1013261/27

xs(2)

cons.

1 :: List(2,3)

map (Immutable)

Map(1 -> 'a', 2 -> 'b', 3 -> 'c') same as

Map((1, 'a'), (2, 'b'), (3, 'c'))

range

accepts start, end and step parameters

Range(1, 5) returns Range(1,2,3,4,5)

Range(1, 10, 2) returns Range(1,3,5,7,9)

range sugar.

1 to 5 same as

1 until 6

1 to 10 by 2

rsync】 【linux】


To copy files from remote to local, maintaining file properties and sym-links (-a), zipping for faster transfer (-z), verbose (-v).

rsync -avz host:file1 :file1 /dest/

rsync -avz /source host:/dest

Copy files using checksum (-c) rather than time to detect if the file has changed. (Useful for validating backups).

rsync -avc /source/ /dest/

Copy contents of /src/foo to destination:

This command will create /dest/foo if it does not already exist

rsync -auv /src/foo /dest

Explicitly copy /src/foo to /dest/foo

rsync -auv /src/foo/ /dest/foo

Copy file from local to remote over ssh with non standard port 1234 to destination folder in remoteuser's home directory

rsync -avz -e "ssh -p1234" /source/file1 remoteuser@X.X.X.X:~/destination/

cluster】 【redis】


Assign new hash slots to receiving node

CLUSTER ADDSLOTS slot [slot ...]

Return the number of failure reports active for a given node

CLUSTER COUNT-FAILURE-REPORTS node-id

Return the number of local keys in the specified hash slot

CLUSTER COUNTKEYSINSLOT slot

Set hash slots as unbound in receiving node

CLUSTER DELSLOTS slot [slot ...]

Forces a slave to perform a manual failover of its master.

CLUSTER FAILOVER [FORCE|TAKEOVER]

Remove a node from the nodes table

CLUSTER FORGET node-id

Return local key names in the specified hash slot

CLUSTER GETKEYSINSLOT slot count

Provides info about Redis Cluster node state

CLUSTER INFO

Returns the hash slot of the specified key

CLUSTER KEYSLOT key

Force a node cluster to handshake with another node

CLUSTER MEET ip port

Get Cluster config for the node

CLUSTER NODES

Reconfigure a node as a slave of the specified master node

CLUSTER REPLICATE node-id

Reset a Redis Cluster node

CLUSTER RESET [HARD|SOFT]

Forces the node to save cluster state on disk

CLUSTER SAVECONFIG

Set the configuration epoch in a new node

CLUSTER SET-CONFIG-EPOCH config-epoch

Bind a hash slot to a specific node

CLUSTER SETSLOT slot IMPORTING|MIGRATING|STABLE|NODE [node-id]

List slave nodes of the specified master node

CLUSTER SLAVES node-id

Get array of Cluster slot to node mappings

CLUSTER SLOTS

Enables read queries for a connection to a cluster slave node

READONLY

Disables read queries for a connection to a cluster slave node

READWRITE

cp】 copy file【linux】


Create a copy of a file

cp ~/Desktop/foo.txt ~/Downloads/foo.txt

Create a copy of a directory

cp -r ~/Desktop/cruise_pics/ ~/Pictures/

Create a copy but ask to overwrite if the destination file already exists

cp -i ~/Desktop/foo.txt ~/Documents/foo.txt

Create a backup file with date

cp foo.txt{,."$(date +%Y%m%d-%H%M%S)"}

svccfg】 Import, export, and modify service configurations (Solaris)【linux】


Validate configuration file:

svccfg validate smf.xml

Export service configurations to file:

svccfg export servicename > smf.xml

Import/update service configurations from file:

svccfg import smf.xml

chmod】 Change the mode of a file or directory【linux】


Add execute for all (myscript.sh)

chmod a+x myscript.sh

Set user to read/write/execute, group/global to read only (myscript.sh), symbolic mode

chmod u=rwx, go=r myscript.sh

Remove write from user/group/global (myscript.sh), symbolic mode

chmod a-w myscript.sh

Remove read/write/execute from user/group/global (myscript.sh), symbolic mode

chmod = myscript.sh

Set user to read/write and group/global read (myscript.sh), octal notation

chmod 644 myscript.sh

Set user to read/write/execute and group/global read/execute (myscript.sh), octal notation

chmod 755 myscript.sh

Set user/group/global to read/write (myscript.sh), octal notation

chmod 666 myscript.sh

Roles

u - user (owner of the file)

g - group (members of file's group)

o - global (all users who are not owner and not part of group)

a - all (all 3 roles above)

Numeric representations

7 - full (rwx)

6 - read and write (rw-)

5 - read and execute (r-x)

4 - read only (r--)

3 - write and execute (-wx)

2 - write only (-w-)

1 - execute only (--x)

0 - none (---)

logical】 【mongo】


OR

db.books.find( { $or: [{year: {$lte: 2008}}, {year: {$eq: 2016}}]} )

AND

db.books.find( { $and: [{year: {$eq: 2008}}, {category: {$eq: "Fiction"}}]} )

NOT

db.books.find( {$not: {year: {$eq: 2016} }})

NOR

db.books.find( { $nor: [{year: {$lte: 2008}}, {year: {$eq: 2016}}]} )

doc】 【python】


Get the documentation string for an python object from shell

we use itertools.starmap as an example

python -c 'import inspect; import itertools; print inspect.getdoc(itertools.starmap)'

Get the documentation string for an object from python

we use itertools.starmap as an example

print inspect.getdoc(itertools.starmap)

In a interactive python shell

help(itertools.starmap)

In a interactive IPython shell

itertools.starmap?

ssh-copy-id】 【linux】


To copy a key to a remote host:

ssh-copy-id username@host

To copy a key to a remote host on a non-standard port:

ssh-copy-id username@host -p 2222

To copy a key to a remote host on a non-standard port with non-standard ssh key:

ssh-copy-id ~/.ssh/otherkey "username@host -p 2222"

chkntfs】 Check the NTFS file system with CHKDSK【win】


Syntax

      CHKNTFS drive: [...]

      CHKNTFS /C drive: [...]

      CHKNTFS /X drive: [...]

      CHKNTFS /t[:Time]

      CHKNTFS /D

Key

   drive Specifies a drive letter.

   /C Check - schedules chkdsk to be run at the next reboot.

   /X Exclude a drive from the default boot-time check.

        Excluded drives are not accumulated between command invocations.

   /T Change the Autochk.exe initiation countdown time (time in seconds)

        If you don’t specify Time: displays the current countdown time.

   /D Restore the machine to the default behavior; all drives are

        checked at boot time and chkdsk is run on those that are dirty.

        This undoes the effect of the /X option.

If no switches are specified, CHKNTFS will display the status of the dirty bit for each drive.

ControlStructures】 【scala】


conditional

if (check) happy else sad

conditional sugar

if (check) happy same as

if (check) happy else ()

multiple conditions

if (check) happy else if(secondCheck) lessHappy else ()

while loop

while (x < 5) { println(x); x += 1}

do while loop.

do { println(x); x += 1} while (x < 5)

break

slides: https:www.slideshare.net/Odersky/fosdem-2009-1013261/21

import scala.util.control.Breaks._

breakable {

  for (x <- xs) {

    if (Math.random < 0.1) break

  }

}

for comprehension: filter/map

for (x <- xs if x%2 == 0) yield x*10

same as

xs.filter(_%2 == 0).map(_*10)

for comprehension: destructuring bind

for ((x,y) <- xs zip ys) yield x*y

same as

(xs zip ys) map { case (x,y) => x*y }

for comprehension: cross product

for (x <- xs; y <- ys) yield x*y

same as

xs flatMap {x => ys map {y => x*y}}

for comprehension: imperative-ish sprintf-style

http:docs.oracle.com/javase/6/docs/api/java/util/Formatter.html#syntax

for (x <- xs; y <- ys) {

  println("%d/%d = %.1f".format(x, y, x/y.toFloat))

}

for comprehension: iterate including the upper bound

for (i <- 1 to 5) {

  println(i)

}

for comprehension: iterate omitting the upper bound

for (i <- 1 until 5) {

  println(i)

}

recursion

can yield a "java.lang.StackOverflowError" with large lists

this is because each recursive call of the function is waiting for the evaluation of the next

def sum(ints: List[Int]): Int = ints match {

  case Nil => 0

  case x :: tail => x + sum(tail)

}

tail recursion

this type of recursion will not throw StackOverflowError

this is because each recursive call of the function is fully evaluated

def sum(ints: List[Int], accum: Int): Int = ints match {

  case Nil => accum

  case x :: tail => sum(tail, accum + x)

}

transactions】 【redis】


Discard all commands issued after MULTI

DISCARD

Execute all commands issued after MULTI

EXEC

Mark the start of a transaction block

MULTI

Forget about all watched keys

UNWATCH

Watch the given keys to determine execution of the MULTI/EXEC block

WATCH key [key ...]

DNSCMD】 Manage DNS servers, unattended setup and configuration of new DNS servers.【win】


Syntax

      DnsCmd ServerName Command [Command Parameters]

    ServerName:

       IP address or host name -- remote or local DNS server

       . -- DNS server on local machine

    Command:

    /ageallrecords Set the current time on all time stamps in a zone or node.

    /clearcache Clear the DNS server cache.

    /config Reset the DNS server or zone configuration.

    /createbuiltindirectorypartitions Create the built-in DNS application directory partitions.

    /createdirectorypartition Create a DNS application directory partition.

    /deletedirectorypartition Delete a DNS application directory partition.

    /directorypartitioninfo List information about a DNS application directory partition.

    /enlistdirectorypartition Add a DNS server to the replication set of a DNS application directory partition.

    /enumdirectorypartitions List the DNS application directory partitions for a server.

    /enumrecords List the resource records in a zone.

    /enumzones List the zones hosted by the specified server.

    /exportsettings Write server configuration information to a text file. NEW in Server 2012

                     %systemroot%\system32\dns\DnsSettings.txt

    /info Get server information.

    /ipvalidate Validate remote DNS servers. NEW in Server 2008

    /nodedelete Delete all records for a node in a zone.

    /recordadd Add a resource record to a zone.

    /recorddelete Remove a resource record from a zone.

    /resetforwarders Set DNS servers to forward recursive queries.

    /resetlistenaddresses Set server IP addresses to serve DNS requests.

    /startscavenging Initiate server scavenging.

    /statistics Query or clear server statistics data.

    /unenlistdirectorypartition Remove a DNS server from the replication set of a DNS application directory partition.

    /writebackfiles Save all zone or root-hint data to a file.

    /zoneadd Create a new zone on the DNS server.

    /zonechangedirectorypartition Change the directory partition on which a zone resides.

    /zonedelete Deletes a zone from the DNS server.

    /zoneexport Write the resource records of a zone to a text file.

    /zoneinfo Display zone information.

    /zonepause Pause a zone.

    /zoneprint Display all records in the zone.

    /zonerefresh Force a refresh of the secondary zone from the master zone.

    /zonereload Reload a zone from its database.

    /zoneresetmasters Change the master servers that provide zone transfer information to a secondary zone.

    /zoneresetscavengeservers Change the servers that can scavenge a zone.

    /zoneresetsecondaries Reset secondary information for a zone.

    /zoneresettype Change the zone type.

    /zoneresume Resume a zone.

    /zoneupdatefromds Update an active directory integrated zone with data from active directory Domain Services (AD DS).

    /zonewriteback Save zone data to a file.

Detailed Usage:

 DnsCmd ServerName /AgeAllRecords ZoneName [NodeName] [/Tree] [/f]

    Zone -- ZoneName

    ZoneName -- FQDN of a zone

    NodeName -- name or node or subtree in which to enable aging

                   - "@" for zone root OR

                   - FQDN of a node (name with a '.' at the end) OR

                   - single label for name relative to zone root

    /Tree -- force aging on entire subtree of node

                    or entire zone if node not given

    /f -- execute without asking for confirmation

 DnsCmd ServerName /clearcache

 DnsCmd ServerName /Config ZoneName Property Value

   run DnsCmd /Config /? for more

 DnsCmd ServerName /CreateBuiltinDirectoryPartitions Option

   run DnsCmd /CreateBuiltinDirectoryPartitions /? for more

 DnsCmd ServerName /CreateDirectoryPartition FQDN of partition

 DnsCmd ServerName /DeleteDirectoryPartition FQDN of partition

 DnsCmd ServerName /DirectoryPartitionInfo FQDN of partition

 DnsCmd ServerName /EnlistDirectoryPartition FQDN of partition

 DnsCmd ServerName /EnumDirectoryPartitions [/Custom]

 DnsCmd ServerName /EnumRecords ZoneName NodeName [DataOptions] [ViewOptions]

   run DnsCmd /EnumRecords /? for more

 DnsCmd ServerName /EnumZones [Filter1 Filter2 ...]

   run DnsCmd /EnumZones /? for more

 DnsCmd ServerName /exportsettings

 DnsCmd Server /Info [Property]

   run DnsCmd /Info /? for more

 DnsCmd ServerName /IpValidate Context [ZoneName] [IPAddress] ..]

  Tests remote DNS server IP addresses

  Context can be one of:

    /DnsServers-- test that IPs are DNS servers

    /Forwarders -- test IPs to use as forwarders

    /RootHints -- test IPs to use as root hints

    /ZoneMasters -- test IPs to use as master servers for the zone named ZoneName

 DnsCmd ServerName /NodeDelete Zone NodeName [/Tree] [/f]

   run DnsCmd /NodeDelete /? for more

 DnsCmd ServerName /RecordAdd Zone NodeName [/Aging] [/OpenAcl] [/CreatePTR] [Ttl] RRType RRData

   run DnsCmd /RecordAdd /? for more

 DnsCmd ServerName /RecordDelete Zone NodeName RRType RRData [/f]

   run DnsCmd /RecordDelete /? for more

 DnsCmd ServerName /ResetForwarders [IPAddress] ...] [ /[No]Slave ] [/TimeOut Time]

   run DnsCmd /ResetForwarders /? for more

 DnsCmd ServerName /ResetListenAddresses [ListenAddress] ...]

  ListenAddress -- an IP address belonging to the DNS server

    Default: listen to all server IP Address(es) for DNS requests

 DnsCmd ServerName /startscavenging

 DnsCmd ServerName /Statistics [StatId | /Clear]

   run DnsCmd /RecordDelete /? for a list of StatIds

 DnsCmd ServerName /UnenlistDirectoryPartition FQDN of partition

 DnsCmd ServerName /WriteBackFiles [ZoneName]

  ZoneName -- FQDN of a zone whose datafile to be written back

    Default: write back datafile for all dirty zones

 DnsCmd ServerName /ZoneAdd ZoneName ZoneType [Options]

  ZoneName -- FQDN of zone

   run DnsCmd /ZoneAdd /? for more

 DnsCmd ServerName /ZoneChangeDirectoryPartition ZoneName NewPartition

    ZoneName -- FQDN of zone to move to new partition

    NewPartition -- FQDN of new directory partition or one of:

                         /domain - domain directory partition

                         /forest - forest directory partition

                         /legacy - legacy directory partition

 DnsCmd ServerName /ZoneDelete ZoneName [/DsDel] [/f]

   /DsDel -- Delete Zone from DS

   /f -- Execute without asking for confirmation

   Default: delete zone from DNS sever, but NOT from DS

 DnsCmd ServerName /ZoneExport ZoneName ZoneExportFile (%systemroot%\system32\dns)

    ZoneName -- FQDN of zone to export

    /Cache -- export cache

 DnsCmd Server /ZoneInfo ZoneName [Property]

  Property -- zone property to view

  Examples:

    AllowUpdate

    DsIntegrated

    Aging

    RefreshInterval

    NoRefreshInterval

 DnsCmd ServerName /ZonePause ZoneName

 DnsCmd ServerName /ZonePrint [ZoneName] [/Detail]

  ZoneName -- name of the zone (use ..Cache for DNS server cache)

  /Detail -- explicit RPC node contents

 DnsCmd ServerName /ZoneResetType ZoneName Property [Options]

  ZoneName -- FQDN of zone

   run DnsCmd /ZoneResetType /? for more

 DnsCmd ServerName /ZoneRefresh ZoneName

 DnsCmd ServerName /ZoneReload ZoneName

 DnsCmd ServerName /ZoneResetMasters ZoneName [/Local] [Server IPs]

    /Local -- Set the local master list for DS integrated zones.

    Server IPs -- List of one or more IP addresses of master servers for

           this zone. Masters may include the primary or other secondaries

           for the zone, but should not make the replication graph cyclic.

 DnsCmd ServerName /ZoneResetScavengeServers ZoneName [Server IPs]

    Server IPs -- list of one or more IP addresses of servers to scavenge

           this zone; if no addresses given ALL servers hosting this zone

           will be allowed to scavenge the zone.

 DnsCmd ServerName /ZoneResetSecondaries ZoneName

               [Security] [SecondaryIPAddress] ...]

               [Notify] [NotifyIPAddress] ...]

   run DnsCmd /ZoneResetSecondaries /? for more

 DnsCmd ServerName /ZoneResume ZoneName

 DnsCmd ServerName /ZoneUpdateFromDs ZoneName

 DnsCmd ServerName /ZoneWriteBack ZoneName

DNSCMD may be removed in a future version of Windows, Microsoft recommend moving over to the DNS cmdlets in PowerShell (Get-command -module DnsServer).

Examples

Backup Zone1.com in an Active Directory-integrated zone:

dnscmd DC1 /zoneexport Zone1.com backup\zone1.com.dns.bak

This will create a file in %systemroot%\system32\dns\backup

columns】 【postgresql】


Add column

ALTER TABLE IF EXISTS

ADD [];

Update column

ALTER TABLE IF EXISTS

ALTER TYPE [];

Delete column

ALTER TABLE IF EXISTS

DROP ;

Update column to be an auto-incrementing primary key

ALTER TABLE

ADD COLUMN SERIAL PRIMARY KEY;

Insert into a table, with an auto-incrementing primary key

INSERT INTO

VALUES (DEFAULT, );

--

INSERT INTO (,)

VALUES ( , );

COMPRESS】 Compress one or more files.【win】


Syntax

      COMPRESS [-R] [-D] [-S] [ -Z | -ZX ] Source Destination

      COMPRESS -R [-D] [-S] [ -Z | -ZX ] Source [Destination]

Key

   -R Rename compressed files.

   -D Update compressed files only if out of date.

   -S Suppress copyright information.

   -ZX LZX compression. This is default compression.

   -Z MS-ZIP compression.

 Source Source file specification. Wildcards can be used.

Destination

        Destination file | path specification.

        Destination can be a directory.

If Source is multiple files and -r is not specified, Destination must be a directory.

Examples:

COMPRESS demo.txt compressed.txt

COMPRESS -R *.*

COMPRESS -R *.exe *.dll compressed_dir

performance】 【postgresql】


Show the query plan for a query

EXPLAIN query;

Show and execute the query plan for a query

EXPLAIN ANALYZE query;

Collect statistics

ANALYZE table_name;

emacs】 【linux】


Basics

    C-x C-f "find" file i.e. open/create a file in buffer

    C-x C-s save the file

    C-x C-w write the text to an alternate name

    C-x C-v find alternate file

    C-x i insert file at cursor position

    C-x b create/switch buffers

    C-x C-b show buffer list

    C-x k kill buffer

    C-z suspend emacs

    C-X C-c close down emacs

Basic movement

    C-f forward char

    C-b backward char

    C-p previous line

    C-n next line

    M-f forward one word

    M-b backward one word

    C-a beginning of line

    C-e end of line

    C-v one page up

    M-v scroll down one page

    M-< beginning of text

    M-> end of text

Editing

    M-n repeat the following command n times

    C-u repeat the following command 4 times

    C-u n repeat n times

    C-d delete a char

    M-d delete word

    M-Del delete word backwards

    C-k kill line

    C-Space Set beginning mark (for region marking for example)

    C-W "kill" (delete) the marked region

    M-W copy the marked region

    C-y "yank" (paste) the copied/killed region/line

    M-y yank earlier text (cycle through kill buffer)

    C-x C-x exchange cursor and mark

    C-t transpose two chars

    M-t transpose two words

    C-x C-t transpose lines

    M-u make letters uppercase in word from cursor position to end

    M-c simply make first letter in word uppercase

    M-l opposite to M-u

Important

    C-g quit the running/entered command

    C-x u undo previous action

    M-x revert-buffer RETURN

                (insert like this) undo all changes since last save

    M-x recover-file RETURN

                Recover text from an autosave-file

    M-x recover-session RETURN

                if you edited several files

Online-Help

    C-h c which command does this keystroke invoke

    C-h k which command does this keystroke invoke and what does it do?

    C-h l what were my last 100 typed keys

    C-h w what key-combo does this command have?

    C-h f what does this function do

    C-h v what\'s this variable and what is it\'s value

    C-h b show all keycommands for this buffer

    C-h t start the emacs tutorial

    C-h i start the info reader

    C-h C-k start up info reader and go to a certain key-combo point

    C-h F show the emacs FAQ

    C-h p show infos about the Elisp package on this machine

Search/Replace

    C-s Search forward

    C-r search backward

    C-g return to where search started (if you are still in search mode)

    M-% query replace

    Space or y replace this occurence

    Del or n don\'t replace

    . only replace this and exit (replace)

    , replace and pause (resume with Space or y)

    ! replace all following occurences

    ^ back to previous match

    RETURN or q quit replace

Search/Replace with regular expressions

Characters to use in regular expressions:

    ^ beginning of line

    $ end of line

    . single char

    .* group or null of chars

    \< beginning of a word

    \> end of a word

    [] every char inside the backets (for example [a-z] means every small letter)

    M C-s RETURN search for regular expression forward

    M C-r RETURN search for regular expression backward

    M C-s incremental search

    C-s repeat incremental search

    M C-r incremental search backwards

    C-r repeat backwards

    M-x query-replace-regexp

                search and replace

Window-Commands

    C-x 2 split window vertically

    C-x o change to other window

    C-x 0 delete window

    C-x 1 close all windows except the one the cursors in

    C-x ^ enlarge window

    M-x shrink-window

                command says it ;-)

    M C-v scroll other window

    C-x 4 f find file in other window

    C-x 4 o change to other window

    C-x 4 0 kill buffer and window

    C-x 5 2 make new frame

    C-x 5 f find file in other frame

    C-x 5 o change to other frame

    C-x 5 0 close this frame

Bookmark commands

    C-x r m set a bookmark at current cursor pos

    C-x r b jump to bookmark

    M-x bookmark-rename

    M-x bookmark-delete

    M-x bookmark-save

    C-x r l list bookmarks

    d mark bookmark for deletion

    r rename bookmark

    s save all listed bookmarks

    f show bookmark the cursor is over

    m mark bookmarks to be shown in multiple window

    v show marked bookmarks (or the one the cursor is over)

    t toggle listing of the corresponding paths

    w path to this file

    x delete marked bookmarks

    q quit bookmark list

    M-x bookmark-write

                write all bookmarks in given file

    M-x bookmark-load

                load bookmark from given file

Shell

    M-x shell starts shell modus

    C-c C-c same as C-c under unix (stop running job)

    C-d delete char forward

    C-c C-d Send EOF

    C-c C-z suspend job (C-z under unix)

    M-p show previous commands

DIRectory EDitor (dired)

    C-x d start up dired

    C (large C) copy

    d mark for erase

    D delete right away

    e or f open file or directory

    g reread directory structure from file

    G change group permissions (chgrp)

    k delete line from listing on screen (don\'t actually delete)

    m mark with *

    n move to next line

    o open file in other window and go there

    C-o open file in other window but don\'t change there

    P print file

    q quit dired

    Q do query-replace in marked files

    R rename file

    u remove mark

    v view file content

    x delete files marked with D

    z compress file

    M-Del remove all marks (whatever kind)

    ~ mark backup files (name~ files) for deletion

mark auto-save files (#name#) for deletion

    */ mark directory with * (C-u * removes that mark again)

    = compare this file with marked file

    M-= compare this file with it\'s backup file

    ! apply shell command to this file

    M-} change to the next file marked with * od D

    M-{ change to the previous file marked with * od D

    % d mark files described through regular expression for deletion

    % m mark files described through regular expression for deletion (with *)

    1. create directory

    changed to next dir change to previous dir

        s toggle between sorting by name or date

        M-x speedbar starts up a separate window with a directory view

    Telnet

        M-x telnet starts up telnet-modus

        C-d either delete char or send EOF

        C-c C-c stop running job (similar to C-c under unix)

        C-c C-d send EOF

        C-c C-o clear output of last command

        C-c C-z suspend execution of command

        C-c C-u kill line backwards

        M-p recall previous command

    Text

    Works only in text mode

        M-s center line

        M-S center paragraph

        M-x center-region

    Macro-commands

        C-x ( start macro definition

        C-x ) end of macro definition

        C-x e execute last defined macro

        M-n C-x e execute last defined macro n times

        M-x name-last-kbd-macro

                    give name to macro (for saving)

        M-x insert-keyboard-macro

                    save named macro into file

        M-x load-file

                    load macro

        M-x macroname

                    execute macroname

    Programming

        M C-\ indent region between cursor and mark

        M-m move to first (non-space) char in this line

        M-^ attach this line to previous

        M-; formatize and indent comment

    C, C++ and Java Modes

        M-a beginning of statement

        M-e end of statement

        M C-a beginning of function

        M C-e end of function

        C-c RETURN Set cursor to beginning of function and mark at the end

        C-c C-q indent the whole function according to indention style

        C-c C-a toggle modus in which after electric signs (like {}:\';./*) emacs does the indention

        C-c C-d toggle auto hungry mode in which emacs deletes groups of spaces with one del-press

        C-c C-u go to beginning of this preprocessor statement

        C-c C-c comment out marked area

    More general

        M-x outline-minor-mode

                    collapses function definitions in a file to a mere {...}

        M-x show-subtree

                    If you are in one of the collapsed functions, this un-collapses it

    In order to achieve some of the feats coming up now you have to run etags *.c *.h *.cpp

    (or what ever ending you source files have) in the source directory

        M-. (Meta dot) If you are in a function call, this will take you to it\'s definition

        M-x tags-search ENTER

                    Searches through all you etaged

        M-, (Meta comma) jumps to the next occurence for tags-search

        M-x tags-query-replace yum.

                    This lets you replace some text in all the tagged files

    GDB (Debugger)

        M-x gdb starts up gdm in an extra window

    Version Control

        C-x v d show all registered files in this dir

        C-x v = show diff between versions

        C-x v u remove all changes since last checkin

        C-x v ~ show certain version in different window

        C-x v l print log

        C-x v i mark file for version control add

        C-x v h insert version control header into file

        C-x v r check out named snapshot

        C-x v s create named snapshot

        C-x v a create changelog file in gnu-style

    redis-cli】 Opens a connection to a Redis server【Redis】


    Connect to the local server:

    redis-cli

    Connect to a remote server on the default port (6379):

    redis-cli -h host

    Connect to a remote server specifying a port number:

    redis-cli -h host -p port

    Specify a password:

    redis-cli -a password

    Execute Redis command:

    redis-cli redis_command

    List Redis keys with prefix "prefix:"

    redis-cli KEYS "prefix:*"

    Delete Redis key abc

    redis-cli DEL abc

    PatternMatching】 【scala】


    use case in function args for pattern matching.

    (xs zip ys) map { case (x,y) => x*y } GOOD

    (xs zip ys) map( (x,y) => x*y ) BAD

    "v42" is interpreted as a name matching any Int value, and "42" is printed.

    BAD

    val v42 = 42

    Some(3) match {

      case Some(v42) => println("42")

      case _ => println("Not 42")

    }

    "v42" with backticks is interpreted as the existing val v42, and “Not 42” is printed.

    GOOD

    val v42 = 42

    Some(3) match {

      case Some(v42) => println("42")

      case _ => println("Not 42")

    }

    UppercaseVal is treated as an existing val, rather than a new pattern variable, because it starts with an uppercase letter.

    Thus, the value contained within UppercaseVal is checked against 3, and “Not 42” is printed.

    GOOD

    val UppercaseVal = 42

    Some(3) match {

      case Some(UppercaseVal) => println("42")

      case _ => println("Not 42")

    }

    Creating an alias for a match

    This will maintain the original value passed into the match function, using the '@' symbol, and print "Matched Some(3)"

    Some(3) match {

        case foundSome @ Some(_) => println("Matched " + foundSome)

        case _ => println("Matched nothing")

    }

    Case Classes

    This method allows you to match on any combination of properties of a case class

    case class Example(a: Int, b: String, c: Boolean)

    Example(1, "word", true) match {

        case Example(3, _, _) => println("Matches any Example where a = 3")

        case Example(_, "foo", _) => println("Matches any Example where b = foo")

        case Example(_, _, false) => println("Matches any Example where c = false")

        case Example(1, "word", true) => println("Matches our Example")

        case Example(_, _, _) => println("Matches any other Example")

    }

    prctl】 Get or set the resource controls of running processes, Tasks, and projects (Solaris)【linux】


    Examine process limits and permissions:

    prctl ${PID}

    Examine process limits and permissions in machine parseable format:

    prctl -P ${PID}

    Get specific limit for a running process:

    prctl -n process.max-file-descriptor ${PID}

    wc】 Count the number【linux】


    Count the number of words (file or STDIN)

    wc -w /path/to/foo.txt

    cat /path/to/foo.txt | wc -w

    Count the number of lines (file or STDIN)

    wc -l /path/to/foo.txt

    cat /path/to/foo.txt | wc -l

    Count the number of bytes (file or STDIN)

    wc -c /path/to/foo.txt

    cat /path/to/foo.txt | wc -c

    Count files and directories at a given location

    ls -l | wc -l

    If you ever use wc in a shell script and need to compare the output with an int you can

    clean the output (wc returns extra characters around the integer) by using xargs:

    ls -l | wc -l | xargs

    xctool】 Tool for building Xcode projects (Mac OS X)【linux】


    Build a single project without any workspace:

    xctool -project YourProject.xcodeproj -scheme YourScheme build

    Build a project that is part of a workspace:

    xctool -workspace YourWorkspace.xcworkspace -scheme YourScheme build

    Clean, build and execute all the tests:

    xctool -workspace YourWorkspace.xcworkspace -scheme YourScheme clean build test

    packages】 【scala】


    wildcard import.

    import scala.collection._

    selective import.

    import scala.collection.Vector

    import scala.collection.{Vector, Sequence}

    renaming import.

    import scala.collection.{Vector => Vec28}

    import all from java.util except Date.

    import java.util.{Date => _, _}

    declare a package.

    package pkg at start of file

    package pkg { ... }

    recursion】 【python】


    Simple Factorial Python Recursion

    def factorial(n) :

        if n == 0 :

            return 1

        else :

            return n * factorial(n-1)

    Simple Greatest Common Divisor Recursion

    def gcd(x, y) :

        if y == 0 :

            return x

        else :

            return gcd(y, x%y)

    dict】 Chinese English translation tool under command line【linux】


    A list of all the available dictionaries can be queried by executing

    dict -I

    translate "understand" to dutch

    dict -d fd-eng-nld understand

    show available dict databases

    dict -D

    percol】 adds flavor of interactive filtering to the traditional pipe concept of UNIX shell 【linux】


    to install percol

    sudo pip install percol

    interactive pgrep version

    ps aux | percol | awk '{ print $2 }'

    interactive pkill version

    ps aux | percol | awk '{ print $2 }' | xargs kill

    wacaw】 A little command-line tool for Mac OS X that allows you to capture both still pictures and video from an attached camera【linux】


    Take a picture from webcam:

    wacaw filename

    Record a video:

    wacaw --video filename -D duration_in_seconds

    Take a picture with custom resolution:

    wacaw -x width -y height filename

    Copy image just taken to clipboard:

    wacaw --to-clipboard

    List the devices available:

    wacaw -L

    exec】 【linux】


    Shell builtin command

    It can start a new process to replace the shell, without a new process creation.

    It can make redirections take effect in the current shell

    Redirect the output of an entire shell script within the script itself

    Only stdout:

    exec > foo.log

    Redirect the output of an entire shell script within the script itself

    Stdout and stderr:

    exec > foo.log 2>&1

    Copy output to a log file

    exec > >(tee -ia foo.log)

    exec 2> >(tee -ia foo.log >&2)

    class】 classes are like structs, but everything is by default private【cpp】


    Declaration

    ObjectName className {

         Sets everything below it to be private.

        private:

             Declaration of variables

            int a;

            string b;

             Implement any private / helper functions below

         Sets everything below it to be public.

        public:

             Constructor

            structName(new_a, new_b) {

                a = new_a;

                b = new_b;

            }

             accessors or getters functions

            int getA() {

                return a;

            }

            string getB() {

                return b;

            }

             mutators or setter functions

            void setA(int new_a) {

                a = new_a;

            }

            void setB(int new_b) {

                b = new_b;

            }

             Implement any public functions below

    };

    Accessing PUBLIC variables

    ObjectName v = structName(5, "Hello"); Creates a struct via the constructor

    std::cout << v.a << " " << v.b << std::endl; Prints to console "5 Hello"

    dscacheutil】 Gather information, statistics and initiate queries to the Directory Service cache.【linux】


    Flush the DNS cache

    in OS X 10.9 Mavericks

    dscacheutil -flushcache

    to clear DNS cache in 10.7 and 10.8

    killall -HUP mDNSResponder

    Show DNS resolver statistics (Mac OS X)

    dscacheutil -statistics

    DISPLAYSWITCH】 Specify which display to use and how to use it.【win】


    Syntax

          DISPLAYSWITCH /Option

    Options

           /internal Switch to use the primary display only.

           1 All other connected displays will be disabled.

           /clone The primary display will be mirrored on a second screen.

           2

           /extend Expand the Desktop to a secondary display.

           3 This allows one desktop to span multiple displays. (Default).

           /external Switch to the external display only (second screen).

           4 The current main display will be disabled.

    Running DisplaySwitch.exe without any options will open a GUI.

    The command is located at: "%SystemRoot%\System32\DisplaySwitch.exe"

    Examples

    Mirror the current Desktop on a secondary display:

    C:\> DisplaySwitch /clone

    Extend the Desktop to a secondary display:

    C:\> DisplaySwitch 3

    crypt】 【linux】


    crypt (Bash-Snippets)

    A wrapper around openssl that facilitates encrypting and decrypting files

    Encrypt a file

    crypt -e fileToEncrypt outputFile

    Decrypt a file

    crypt -d fileToDecrypt outputFile

    convert】 【linux】


    To resize an image to a fixed width and proportional height:

    convert original-image.jpg -resize 100x converted-image.jpg

    To resize an image to a fixed height and proportional width:

    convert original-image.jpg -resize x100 converted-image.jpg

    To resize an image to a fixed width and height:

    convert original-image.jpg -resize 100x100 converted-image.jpg

    To resize an image and simultaneously change its file type:

    convert original-image.jpg -resize 100x converted-image.png

    To resize all of the images within a directory:

    To implement a for loop:

    for file in ls original/image/path/;

        do new_path=${file%.*};

        new_file=basename $new_path;

        convert $file -resize 150 conerted/image/path/$new_file.png;

    done

    Make text annotatation (text = Flower)

    convert flower.jpg -font courier -fill white -pointsize 20 -annotate +50+50 'Flower' flower_annotate1.jpg

    Crop an image

    convert flower.jpg -crop 128×128+50+50 flower_crop.jpg

    Rotate an image

    convert flower.jpg -rotate 45 flower_rotate45.jpg

    Add a border

    convert -border 1x1 -bordercolor "#FFFFFF" image.png new-image.png

    Convert PNG to JPEG (with 70% quality)

    convert -quality 70 image.png new_image.jpg

    sockstat】 【linux】


    To view which users/processes are listening to which ports:

    sudo sockstat -l

    tcpdump】 packet analyzer【linux】


    TCPDump is a packet analyzer. It allows the user to intercept and display TCP/IP

    and other packets being transmitted or received over a network. (cf Wikipedia).

    Note: 173.194.40.120 => google.com

    Intercepts all packets on eth0

    tcpdump -i eth0

    Intercepts all packets from/to 173.194.40.120

    tcpdump host 173.194.40.120

    Intercepts all packets on all interfaces from / to 173.194.40.120 port 80

    -nn => Disables name resolution for IP addresses and port numbers.

    tcpdump -nn -i any host 173.194.40.120 and port 80

    Make a grep on tcpdump (ASCII)

    -A => Show only ASCII in packets.

    -s0 => By default, tcpdump only captures 68 bytes.

    tcpdump -i -A any host 173.194.40.120 and port 80 | grep 'User-Agent'

    With ngrep

    -d eth0 => To force eth0 (else ngrep work on all interfaces)

    -s0 => force ngrep to look at the entire packet. (Default snaplen: 65536 bytes)

    ngrep 'User-Agent' host 173.194.40.120 and port 80

    Intercepts all packets on all interfaces from / to 8.8.8.8 or 173.194.40.127 on port 80

    tcpdump 'host ( 8.8.8.8 or 173.194.40.127 ) and port 80' -i any

    Intercepts all packets SYN and FIN of each TCP session.

    tcpdump 'tcp[tcpflags] & (tcp-syn|tcp-fin) != 0'

    To display SYN and FIN packets of each TCP session to a host that is not on our network

    tcpdump 'tcp[tcpflags] & (tcp-syn|tcp-fin) != 0 and not src and dst net local_addr'

    To display all IPv4 HTTP packets that come or arrive on port 80 and that contain only data (no SYN, FIN no, no packet containing an ACK)

    tcpdump 'tcp port 80 and (((ip[2:2] - ((ip[0]&0xf)<<2)) - ((tcp[12]&0xf0)>>2)) != 0)'

    Saving captured data

    tcpdump -w file.cap

    Reading from capture file

    tcpdump -r file.cap

    Show content in hexa

    Change -x to -xx => show extra header (ethernet).

    tcpdump -x

    Show content in hexa and ASCII

    Change -X to -XX => show extra header (ethernet).

    tcpdump -X

    Note on packet maching:

    Port matching:

    - portrange 22-23

    - not port 22

    - port ssh

    - dst port 22

    - src port 22

    Host matching:

    - dst host 8.8.8.8

    - not dst host 8.8.8.8

    - src net 67.207.148.0 mask 255.255.255.0

    - src net 67.207.148.0/24

    certutil】 【win】


    Dump and display certification authority (CA) configuration information, configure Certificate Services, back up and restore CA components, verify certificates, key pairs or certificate chains.

    Syntax:

      Dump (read config information) from a certificate file

      CertUtil [Options] [-dump] [File]

        Options: [-f] [-silent] [-split] [-p Password] [-t Timeout]

      Parse ASN.1 file

      CertUtil [Options] -asn File

        Options: [-f] [decoding_type]

      Decode a Hex-encoded file to binary

      CertUtil [-f] [-v] -decodehex InFile OutFile

      Decode Base64-encoded file to binary

      CertUtil [-f] [-v] -decode InFile OutFile

      Encode a binary file to Base64

      CertUtil [-f] [-v] -encode InFile OutFile [-UnicodeText]

      Encode a file as Hex

      CertUtil [-f] [-v] -encodehex InFile OutFile Format

         Hex encoded files are around 3x larger than base64

         Examples of the Hex formats:

           certutil -encodehex -f strings64.exe strings12.hex 12 - One line HEX value without spaces, columns, addresses,

           certutil -encodehex -f strings64.exe strings5.hex 5 - without addresses.

           certutil -encodehex -f strings64.exe strings2.hex 2 - pure binary (rarely used).

           certutil -encodehex -f strings64.exe strings1.hex 1 - base64 without certificate headers.

           certutil -encodehex -f strings64.exe strings0.hex 0 - base64 with certificate headers.

           certutil -encodehex -f strings64.exe strings4.hex 4 - in columns with spaces, without the characters and the addresses.

           certutil -encodehex -f strings64.exe strings7.hex 7 - base64 - X509 without headers (slightly bigger than the normal b64)

           certutil -encodehex -f strings64.exe strings8.hex 8 - base64 - x509 with headers.

      Deny pending request

      CertUtil [Options] -deny RequestId

        Options: [-v] [-config Machine\CAName]

      Resubmit pending request

      CertUtil [Options] -resubmit RequestId

        Options: [-v] [-config Machine\CAName]

      Set attributes for pending request

      CertUtil [Options] -setattributes RequestId AttributeString

        Options: [-v] [-config Machine\CAName]

        RequestId : Numeric Request Id of pending request.

        AttributeString : Request Attribute name and value pairs.

        Names and values are colon separated. Multiple name, value pairs are newline separated.

        Example: "CertificateTemplate:User\nEMail:User@Domain.com"

        Each "\n" sequence is converted to a newline separator.

     Set extension for pending request

      CertUtil [Options] -setextension RequestId ExtensionName Flags {Long | Date | String | @InFile}

        Options: [-v] [-config Machine\CAName]

        RequestId : Numeric Request Id of a pending request.

        ExtensionName : ObjectId string of the extension.

        Flags : 0 is recommended. 1 makes the extension critical, 2 disables it, 3 does both.

        If the last parameter is numeric, it is taken as a Long. If it can be parsed as a date, it is taken as a Date.

        If it starts with '@', the rest of the token is the filename containing binary data or an ascii-text hex dump.

        Anything else is taken as a String.

     Revoke Certificate

     CertUtil [Options] -revoke SerialNumber [Reason]

        Options: [-v] [-config Machine\CAName]

        SerialNumber: Comma separated list of certificate serial numbers to revoke

        Reason: numeric or symbolic revocation reason

         0: CRL_REASON_UNSPECIFIED: Unspecified (default)

         1: CRL_REASON_KEY_COMPROMISE: Key Compromise

         2: CRL_REASON_CA_COMPROMISE: CA Compromise

         3: CRL_REASON_AFFILIATION_CHANGED: Affiliation Changed

         4: CRL_REASON_SUPERSEDED: Superseded

         5: CRL_REASON_CESSATION_OF_OPERATION: Cessation of Operation

         6: CRL_REASON_CERTIFICATE_HOLD: Certificate Hold

         8: CRL_REASON_REMOVE_FROM_CRL: Remove From CRL

         -1: Unrevoke: Unrevoke

      Display current certificate disposition

      CertUtil [Options] -isvalid SerialNumber | CertHash

        Options: [-v] [-config Machine\CAName]

      Get default configuration string

      CertUtil [Options] -getconfig

        Options: [-v] [-config Machine\CAName]

      Ping Active Directory Certificate Services Request interface

      CertUtil [Options] -ping [MaxSecondsToWait | CAMachineList]

        Options: [-v] [-config Machine\CAName]

         Request interface CAMachineList -- Comma-separated CA machine name list

         For a single machine, use a terminating comma

         Displays the site cost for each CA machine

      Ping Active Directory Certificate Services Admin interface

      CertUtil [Options] -pingadmin [MaxSecondsToWait | CAMachineList]

        Options: [-v] [-config Machine\CAName]

         Request interface CAMachineList -- Comma-separated CA machine name list

         For a single machine, use a terminating comma

         Displays the site cost for each CA machine

      Display CA Information

      CertUtil [Options] -CAInfo [InfoName [Index | ErrorCode]]

        Options: [-v] [-config Machine\CAName]

        InfoName : indicates the CA property to display. Use "*" for all properties.

        Index : optional zero-based property index

        ErrorCode : numeric error code [-f] [-split] [-config Machine\CAName]

      Retrieve the CA's certificate

      CertUtil [Options] -ca.cert OutCACertFile [Index]

        Options: [-f] [-v] [-split] [-config Machine\CAName]

        OutCACertFile: output file

        Index: CA certificate renewal index (defaults to most recent)

      Retrieve the CA's certificate chain

      CertUtil [Options] -ca.chain OutCACertChainFile [Index]

        Options: [-f] [-v] [-split] [-config Machine\CAName]

        OutCACertChainFile: output file

        Index: CA certificate renewal index (defaults to most recent)

      Get CRL

      CertUtil [Options] -GetCRL OutFile [Index] [delta]

        Options: [-f] [-v] [-split] [-config Machine\CAName]

        Index : CRL index or key index (defaults to CRL for newest key)

        delta : delta CRL (default is base CRL)

      Publish new CRLs [or delta CRLs only]

      CertUtil [Options] -CRL [dd:hh | republish] [delta]

        Options: [-v] [-split] [-config Machine\CAName]

        dd:hh -- new CRL validity period in days and hours

        republish -- republish most recent CRLs

        delta -- delta CRLs only (default is base and delta CRLs)

      Shutdown Active Directory Certificate Services

      CertUtil [Options] -shutdown

        Options: [-v] [-config Machine\CAName]

      Install Certification Authority certificate

      CertUtil [Options] -installCert [CACertFile]

        Options: [-f] [-v] [-silent] [-config Machine\CAName]

      Renew Certification Authority certificate

      CertUtil [Options] -renewCert [ReuseKeys] [Machine\ParentCAName]

        Options: [-f] [-v] [-silent] [-config Machine\CAName]

        Use -f to ignore an outstanding renewal request, and generate a new request.

      Dump Certificate Schema

      CertUtil [Options] -schema [Ext | Attrib | CRL]

        Options: [-v] [-split] [-config Machine\CAName]

        Ext : Extension table

        Attrib : Attribute table

        CRL : CRL table

        Defaults to Request and Certificate table.

      Dump Certificate View

      CertUtil [Options] -view [Queue | Log | LogFail | Revoked | Ext | Attrib | CRL] [csv]

        Options: [-v] [-silent] [-split] [-config Machine\CAName] [-restrict RestrictionList] [-out ColumnList]

        Queue : Request queue.

        Log : Issued or revoked certificates, plus failed requests.

        LogFail : Failed requests.

        Revoked : Revoked certificates.

        Ext : Extension table.

        Attrib : Attribute table.

        CRL : CRL table.

        csv : Output as Comma Separated Values.

        To display the StatusCode column for all entries: -out StatusCode

        To display all columns for the last entry: -restrict "RequestId==$"

        To display RequestId and Disposition for three requests:

        -restrict "RequestId>=37,RequestId<40" -out "RequestId,Disposition"

        To display Row Ids and CRL Numbers for all Base CRLs: -restrict "CRLMinBase=0" -out "CRLRowId,CRLNumber" CRL

        To display Base CRL Number 3: -v -restrict "CRLMinBase=0,CRLNumber=3" -out "CRLRawCRL" CRL

        To display the entire CRL table: CRL Use "Date[+|-dd:hh]" for date restrictions Use "now+dd:hh" for a date relative to the current time.

      Dump Raw Database

      CertUtil [Options] -db

        Options: [-v] [-config Machine\CAName] [-restrict RestrictionList] [-out ColumnList]

      Delete server database row

      CertUtil [Options] -deleterow RowId | Date [Request | Cert | Ext | Attrib | CRL]

        Options: [-f] [-v] [-config Machine\CAName]

        Request : Failed and pending requests (submission date)

        Cert : Expired and revoked certificates (expiration date)

        Ext : Extension table Attrib: Attribute table

        CRL : CRL table (expiration date)

        To delete failed and pending requests submitted by January 22, 2001: 1/22/2001 Request

        To delete all certificates that expired by January 22, 2001: 1/22/2001 Cert

        To delete the certificate row, attributes and extensions for RequestId 37: 37

        To delete CRLs that expired by January 22, 2001: 1/22/2001 CRL [-f] [-config Machine\CAName]

      Backup Active Directory Certificate Services

      CertUtil [Options] -backup BackupDirectory [Incremental] [KeepLog]

        Options: [-f] [-v] [-config Machine\CAName] [-p Password]

        BackupDirectory : directory to store backed up data

        Incremental : perform incremental backup only (default is full backup)

        KeepLog : preserve database log files (default is to truncate log files)

      Backup Active Directory Certificate Services database

      CertUtil [Options] -backupDB BackupDirectory [Incremental] [KeepLog]

        Options: [-f] [-v] [-config Machine\CAName]

        BackupDirectory : directory to store backed up data

        Incremental : perform incremental backup only (default is full backup)

        KeepLog : preserve database log files (default is to truncate log files)

      Backup Active Directory Certificate Services certificate and private key

      CertUtil [Options] -backupKey BackupDirectory

        Options: [-f] [-v] [-config Machine\CAName] [-p Password] [-t Timeout]

        BackupDirectory : directory to store backed up PFX file

      Restore Active Directory Certificate Services

      CertUtil [Options] -restore BackupDirectory

        Options: [-f] [-v] [-config Machine\CAName] [-p Password]

        BackupDirectory : directory containing data to be restored

      Restore Active Directory Certificate Services database

      CertUtil [Options] -restoreDB BackupDirectory

        Options: [-f] [-v] [-config Machine\CAName] [-p Password]

        BackupDirectory : directory containing database files to be restored

      Restore Active Directory Certificate Services certificate and private key

      CertUtil [Options] -restoreKey BackupDirectory | PFXFile

        Options: [-f] [-v] [-config Machine\CAName] [-p Password]

        BackupDirectory : directory containing PFX file to be restored

        PFXFile : PFX file to be restored

      Import certificate and private key

      CertUtil [Options] -importPFX [CertificateStoreName] PFXFile [Modifiers] [-csp Provider]

        Options: [-f] [-v] [-user] [-p Password]

        CertificateStoreName : Certificate store name. See -store.

        PFXFile : PFX file to be imported

        Modifiers : Comma separated list of one or more of the following:

        AT_SIGNATURE : Change the KeySpec to Signature

        AT_KEYEXCHANGE : Change the KeySpec to Key Exchange

        NoExport : Make the private key non-exportable

        NoCert : Do not import the certificate

        NoChain : Do not import the certificate chain

        NoRoot : Do not import the root certificate

        Protect : Protect keys with password

        NoProtect : Do not password protect keys

        Defaults to personal machine store.

      Display dynamic file List

      CertUtil [Options] -dynamicfilelist

        Options: [-v] [-config Machine\CAName]

      Display database locations

      CertUtil [Options] -databaselocations

        Options: [-v] [-config Machine\CAName]

      Generate and display cryptographic hash over a file.

      CertUtil [Options] -hashfile InFile [HashAlgorithm]

        Options: [-v]

      Dump certificate store

      CertUtil [Options] -store [CertificateStoreName [CertId [OutputFile]]]

        Options: [-f] [-v] [-enterprise] [-user] [-GroupPolicy] [-silent] [-split] [-dc DCName]

        CertificateStoreName : Certificate store name.

        CertId : Certificate or CRL match token. This can be a serial number, an SHA-1 certificate, CRL, CTL or public key hash, a numeric cert index (0, 1, and so on), a numeric CRL index (.0, .1, and so on), a numeric CTL index (..0, ..1, and so on), a public key, signature or extension ObjectId, a certificate subject Common Name, an e-mail address, UPN or DNS name, a key container name or CSP name, a template name or ObjectId, an EKU or Application Policies ObjectId, or a CRL issuer Common Name. These can result in multiple matches.

        OutputFile : File to save matching cert.

        Use -user to access a user store instead of a machine store.

        Use -enterprise to access a machine enterprise store.

        Use -service to access a machine service store.

        Use -grouppolicy to access a machine group policy store.

      Add certificate to store

      CertUtil [Options] -addstore CertificateStoreName InFile

        Options: [-f] [-v] [-enterprise] [-user] [-GroupPolicy] [-dc DCName]

        CertificateStoreName : Certificate store name. See -store.

        InFile : Certificate or CRL file to add to store.

      Delete certificate from store

      CertUtil [Options] -delstore CertificateStoreName CertId

        Options: [-f] [-v] [-enterprise] [-user] [-GroupPolicy] [-dc DCName]

        CertificateStoreName : Certificate store name. See -store.

        CertId : Certificate or CRL match token. See -store.

      Verify certificate in store

      CertUtil [Options] -verifystore CertificateStoreName [CertId]

        Options: [-f] [-v] [-enterprise] [-user] [-GroupPolicy] [-silent] [-split] [-dc DCName] [-t Timeout]

        CertificateStoreName : Certificate store name. See -store.

        CertId : Certificate or CRL match token. See -store.

      Repair key association or update certificate properties or key security descriptor

      CertUtil [Options] -repairstore CertificateStoreName CertIdList [PropertyInfFile | SDDLSecurityDescriptor]

        Options: [-f] [-v] [-enterprise] [-user] [-GroupPolicy] [-silent] [-split] [-csp Provider]

        CertificateStoreName : Certificate store name. See -store.

        CertIdList : comma separated list of Certificate or CRL match tokens. See -store CertId description.

        PropertyInfFile : INF file containing external properties:

      Dump certificate store

      CertUtil [Options] -viewstore [CertificateStoreName [CertId [OutputFile]]]

        Options: [-f] [-v] [-enterprise] [-user] [-GroupPolicy] [-dc DCName]

        CertificateStoreName : Certificate store name.

        CertId : Certificate or CRL match token. This can be a serial number, an SHA-1 certificate, CRL, CTL or public key hash, a numeric cert index (0, 1, and so on), a numeric CRL index (.0, .1, and so on), a numeric CTL index (..0, ..1, and so on), a public key, signature or extension ObjectId, a certificate subject Common Name, an e-mail address, UPN or DNS name, a key container name or CSP name, a template name or ObjectId, an EKU or Application Policies ObjectId, or a CRL issuer Common Name. These can result in multiple matches.

        OutputFile : file to save matching cert.

        Use -user to access a user store instead of a machine store.

        Use -enterprise to access a machine enterprise store.

        Use -service to access a machine service store.

        Use -grouppolicy to access a machine group policy store.

      Delete certificate from store

      CertUtil [Options] -viewdelstore [CertificateStoreName [CertId [OutputFile]]]

        Options: [-f] [-v] [-enterprise] [-user] [-GroupPolicy] [-dc DCName]

        CertificateStoreName : Certificate store name.

        CertId : Certificate or CRL match token. This can be a serial number, an SHA-1 certificate, CRL, CTL or public key hash, a numeric cert index (0, 1, and so on), a numeric CRL index (.0, .1, and so on), a numeric CTL index (..0, ..1, and so on), a public key, signature or extension ObjectId, a certificate subject Common Name, an e-mail address, UPN or DNS name, a key container name or CSP name, a template name or ObjectId, an EKU or Application Policies ObjectId, or a CRL issuer Common Name. These can result in multiple matches.

        OutputFile : File to save matching cert.

        Use -user to access a user store instead of a machine store.

        Use -enterprise to access a machine enterprise store.

        Use -service to access a machine service store.

        Use -grouppolicy to access a machine group policy store.

      Publish certificate or CRL to Active Directory

      CertUtil [Options] -dsPublish CertFile [NTAuthCA | RootCA | SubCA | CrossCA | KRA | User | Machine]

        Options: [-f] [-v] [-user] [-dc DCName]

      CertUtil [Options] -dsPublish CRLFile [DSCDPContainer [DSCDPCN]] [-f] [-user] [-dc DCName]

        Options: [-f] [-v] [-user] [-dc DCName]

        CertFile : certificate file to publish

        NTAuthCA : Publish cert to DS Enterprise store

        RootCA : Publish cert to DS Trusted Root store

        SubCA : Publish CA cert to DS CA object

        CrossCA : Publish cross cert to DS CA object

        KRA : Publish cert to DS Key Recovery Agent object

        User : Publish cert to User DS object

        Machine : Publish cert to Machine DS object

        CRLFile : CRL file to publish

        DSCDPContainer : DS CDP container CN, usually the CA machine name

        DSCDPCN : DS CDP object CN, usually based on the sanitized CA short name and key index

        Use -f to create DS object.

      Display AD templates

      CertUtil [Options] -ADTemplate [Template]

        Options: [-f] [-v] [-user] [-ut] [-mt] [-dc DCName]

      Display Enrollment Policy templates

      CertUtil [Options] -Template [Template]

        Options: [-f] [-v] [-user] [-dc DCName] [-user] [-silent] [-PolicyServer URLOrId]

         [-Anonymous] [-Kerberos] [-ClientCertificate ClientCertId] [-UserName UserName] [-p Password]

      Display CAs for template

      CertUtil [Options] -TemplateCAs Template

        Options: [-f] [-v] [-user] [-dc DCName]

      Display templates for CA

      CertUtil [Options] -CATemplates [Template]

        Options: [-f] [-v] [-user] [-ut] [-mt] [-config Machine\CAName] [-dc DCName]

      Set, Verify or Delete CA site names

      CertUtil [Options] -SetCASites [set] [Sitename]

      CertUtil [Options] -SetCASites verify [Sitename]

      CertUtil [Options] -SetCASites delete

        Options: [-f] [-v] [-config Machine\CAName] [-dc DCName]

        Use the -config option to target a single CA (Default is all CAs)

        Sitename is allowed only when targeting a single CA

        Use -f to override validation errors for the specified Sitename

        Use -f to delete all CA site names

      Display, add or delete enrollment server URLs associated with a CA

      CertUtil [Options] -enrollmentServerURL [URL AuthenticationType [Priority] [Modifiers]]

      CertUtil [Options] -enrollmentServerURL URL delete

        Options: [-f] [-config Machine\CAName] [-dc DCName]

        AuthenticationType: Specify one of the following client authentication methods while adding a URL:

            Kerberos : Use Kerberos SSL credentials.

            UserName : Use named account for SSL credentials.

            ClientCertificate : Use X.509 Certificate SSL credentials.

            Anonymous : Use anonymous SSL credentials.

        delete : Delete the specified URL associated with the CA

        Priority : Defaults to '1' if not specified when adding a URL

        Modifiers : Comma separated list of one or more of the following:

            AllowRenewalsOnly : Only renewal requests can be submitted to this CA via this URL

            AllowKeyBasedRenewal : Allow use of a certificate that has no associated account in the AD.

            This applies only with ClientCertificate and AllowRenewalsOnly Mode

      Display AD CAs

      CertUtil [Options] -ADCA [CAName]

        Options: [-f] [-split] [-dc DCName]

      Display Enrollment Policy CAs

      CertUtil [Options] -CA [CAName | TemplateName]

        Options: [-f] [-user] [-silent] [-split] [-PolicyServer URLOrId]

         [-Anonymous] [-Kerberos] [-ClientCertificate ClientCertId] [-UserName UserName] [-p Password]

      Display Enrollment Policy

      CertUtil [Options] -Policy

        Options: [-f] [-user] [-silent] [-split] [-PolicyServer URLOrId] [-Anonymous]

         [-Kerberos] [-ClientCertificate ClientCertId] [-UserName UserName] [-p Password]

      Display or delete Enrollment Policy Cache entries

      CertUtil [Options] -PolicyCache [delete]

        Options: [-f] [-user] [-PolicyServer URLOrId]

        delete: delete Policy Server cache entries

            -f: use -f to delete all cache entries

      Display, add or delete Credential Store entries

      CertUtil [Options] -CredStore [URL]

      CertUtil [Options] -CredStore URL add

      CertUtil [Options] -CredStore URL delete

        Options: [-f] [-user] [-silent] [-Anonymous] [-Kerberos]

            [-ClientCertificate ClientCertId] [-UserName UserName] [-p Password]

        URL : target URL. Use * to match all entries. Use https:machine* to match a URL prefix.

        add : add a Credential Store entry. SSL credentials must also be specified.

        delete : delete Credential Store entries

        -f : use -f to overwrite an entry or to delete multiple entries.

      Install default certificate templates

      CertUtil [Options] -InstallDefaultTemplates

        Options: [-f] [-v] [-dc DCName]

      Display or delete URL cache entries

      CertUtil [Options] -URLCache [URL | CRL | * [delete]]

        Options: [-f] [-v] [-split]

        URL : Cached URL

        CRL : Operate on all cached CRL URLs only

        delete : Delete relevant URLs from the current user's local cache

        -f : Force fetch of a specific URL and update the cache.

        -split : Dump the file to disk

        -v : Will display the whole IE internet history and cache file locations (…\Content.IE5…)

        e.g.

        certutil.exe -urlcache -split -f "https:download.sysinternals.com/files/SysinternalsSuite.zip" pstools.zip

      Pulse autoenrollment events

      CertUtil [Options] -pulse

        Options: [-v] [-user]

      Display Active Directory computer object information

      CertUtil [Options] -MachineInfo DomainName\MachineName$

        Options: [-v]

      Display domain controller information

      CertUtil [Options] -DCInfo [Domain] [Verify | DeleteBad | DeleteAll]

        Options: [-f] [-v] [-user] [-urlfetch] [-dc DCName] [-t Timeout]

        Default is to display DC certs without verification.

      Display Enterprise CA information

      CertUtil [Options] -EntInfo DomainName\MachineName$

        Options: [-f] [-v] [-user]

      Display CA information

      CertUtil [Options] -TCAInfo [DomainDN | -]

        Options: [-f] [-v] [-enterprise] [-user] [-urlfetch] [-dc DCName] [-t Timeout]

      Display smart card information

      CertUtil [Options] -SCInfo [ReaderName [CRYPT_DELETEKEYSET]]

        Options: [-v] [-silent] [-split] [-urlfetch] [-t Timeout]

        CRYPT_DELETEKEYSET : Delete all keys on the smart card

      Manage smart card root certificates

      CertUtil [Options] -SCRoots update [+][InputRootFile] [ReaderName]

      CertUtil [Options] -SCRoots save @OutputRootFile [ReaderName]

      CertUtil [Options] -SCRoots view [InputRootFile | ReaderName]

      CertUtil [Options] -SCRoots delete [ReaderName]

        Options: [-f] [-split] [-p Password]

      Verify public/private key set

      CertUtil [Options] -verifykeys [KeyContainerName CACertFile]

        Options: [-f] [-v] [-user] [-silent] [-config Machine\CAName]

        KeyContainerName : Key container name of the key to verify. Defaults to machine keys. Use -user for user keys.

        CACertFile : Signing or encryption certificate file

        If no arguments are specified, each signing CA cert is verified against its private key.

        This operation can only be performed against a local CA or local keys.

      Verify certificate, CRL or chain

      CertUtil [Options] -verify CertFile [ApplicationPolicyList | - [IssuancePolicyList]]

      CertUtil [Options] -verify CertFile [CACertFile [CrossedCACertFile]]

      CertUtil [Options] -verify CRLFile CACertFile [IssuedCertFile]

      CertUtil [Options] -verify CRLFile CACertFile [DeltaCRLFile]

        Options: [-f] [-v] [-enterprise] [-user] [-silent] [-split] [-urlfetch] [-t Timeout]

        CertFile : Certificate to verify Application

        PolicyList : Optional comma separated list of required Application Policy ObjectIds

        IssuancePolicyList : Optional comma separated list of required Issuance Policy ObjectIds

        CACertFile : Optional issuing CA certificate to verify against

        CrossedCACertFile : optional certificate cross-certified by CertFile

        CRLFile : CRL to verify IssuedCertFile: optional issued certificate covered by CRLFile

        DeltaCRLFile : Optional delta CRL

        If ApplicationPolicyList is specified, chain building is restricted to chains valid for

        the specified Application Policies.

        If IssuancePolicyList is specified, chain building is restricted to chains valid for the

        specified Issuance Policies.

        If CACertFile is specified, fields in CACertFile are verified against CertFile or CRLFile.

        If CACertFile is not specified, CertFile is used to build and verify a full chain.

        If CACertFile and CrossedCACertFile are both specified, fields in CACertFile and CrossedCACertFile

        are verified against CertFile.

        If IssuedCertFile is specified, fields in IssuedCertFile are verified against CRLFile.

        If DeltaCRLFile is specified, fields in DeltaCRLFile are verified against CRLFile.

      Verify AuthRoot or Disallowed Certificates CTL

      CertUtil [Options] -verifyCTL CTLObject [CertDir] [CertFile]

        Options: [-f] [-user] [-split]

        CTLObject : Identifies the CTL to verify:

            AuthRootWU : read AuthRoot CAB and matching certificates from the URL cache. Use -f to download from Windows Update instead.

            DisallowedWU : read Disallowed Certificates CAB and disallowed certificate store file from the URL cache. Use -f to download from Windows Update instead.

            AuthRoot : read registry cached AuthRoot CTL. Use with -f and a CertFile that is not already trusted to force updating the registry cached AuthRoot and Disallowed Certificate CTLs.

            Disallowed : read registry cached Disallowed Certificates CTL. -f has the same behavior as with AuthRoot.

            CTLFileName : file or http: path to CTL or CAB

        CertDir : folder containing certificates matching CTL entries. An http: folder path must end with a path separator. If a folder is not specified with AuthRoot or Disallowed, multiple locations will be searched for matching certificates: local certificate stores, crypt32.dll resources and the local URL cache. Use -f to download from Windows Update when necessary.

        Otherwise defaults to the same folder or web site as the CTLObject.

        CertFile : file containing certificate(s) to verify. Certificates will be matched against CTL entries,

        and match results displayed. Suppresses most of the default output.

      Re-sign CRL or certificate

      CertUtil [Options] -sign InFileList|SerialNumber|CRL OutFileList [StartDate+dd:hh]

         [+SerialNumberList | -SerialNumberList | -ObjectIdList | @ExtensionFile] [-nullsign]

      CertUtil [Options] -sign InFileList|SerialNumber|CRL OutFileList [#HashAlgorithm]

         [+AlternateSignatureAlgorithm | -AlternateSignatureAlgorithm] [-nullsign]

        Options: [-f] [-silent] [-Cert CertId]

        InFileList : comma separated list of Certificate or CRL files to modify and re-sign

        SerialNumber : Serial number of certificate to create. Validity period and other options must not be present.

        CRL : Create an empty CRL. Validity period and other options must not be present.

        OutFileList : comma separated list of modified Certificate or CRL output files. The number of files must match InFileList.

        StartDate+dd:hh : new validity period: optional date plus; optional days and hours validity period;

        If both are specified, use a plus sign (+) separator.

        Use "now[+dd:hh]" to start at the current time. Use "never" to have no expiration date (for CRLs only).

        SerialNumberList : Comma separated serial number list to add or remove

        ObjectIdList : Comma separated extension ObjectId list to remove

        @ExtensionFile : INF file containing extensions to update or remove:

        HashAlgorithm : Name of the hash algorithm preceded by a # sign: #MD2 #MD4 #MD5 #SHA1 #SHA256 #SHA384 or #SHA512

        AlternateSignatureAlgorithm : alternate Signature algorithm specifier

        A minus sign causes serial numbers and extensions to be removed. A plus sign causes serial numbers to be added to a CRL.

        When removing items from a CRL, the list can contain both serial numbers and ObjectIds.

        A minus sign before AlternateSignatureAlgorithm causes the legacy signature format to be used.

        A plus sign before AlternateSignatureAlgorithm causes the alternature signature format to be used.

        If AlternateSignatureAlgorithm is not specified then the signature format in the certificate or CRL is used.

      Create/delete web virtual roots and file shares

      CertUtil [Options] -vroot [delete]

      Create/delete web virtual roots for OCSP web proxy

      CertUtil [Options] -vocsproot [delete]

      Add an Enrollment Server application

      CertUtil [Options] -addEnrollmentServer Kerberos | UserName | ClientCertificate [AllowRenewalsOnly] [AllowKeyBasedRenewal]

        Options: [-f] [-config Machine\CAName]

        Add an Enrollment Server application and application pool if necessary, for the specified CA.

        This command does not install binaries or packages.

        One of the following authentication methods with which the client connects to a Certificate Enrollment Server.

        Kerberos : Use Kerberos SSL credentials

        UserName : Use named account for SSL credentials

        ClientCertificate : Use X.509 Certificate SSL credentials

        AllowRenewalsOnly : Only renewal requests can be submitted to this CA via this URL

        AllowKeyBasedRenewal : Allows use of a certificate that has no associated account in the AD.

        This applies only with ClientCertificate and AllowRenewalsOnly mode.

      Delete an Enrollment Server application

      CertUtil [Options] -deleteEnrollmentServer Kerberos | UserName | ClientCertificate

        Options: [-f] [-config Machine\CAName]

        Delete an Enrollment Server application and application pool if necessary, for the specified CA.

        This command does not remove binaries or packages.

        One of the following authentication methods with which the client connects to a Certificate Enrollment Server.

        Kerberos : Use Kerberos SSL credentials

        UserName : Use named account for SSL credentials

        ClientCertificate : Use X.509 Certificate SSL credentials

      Add a Policy Server application

      CertUtil [Options] -addPolicyServer Kerberos | UserName | ClientCertificate [KeyBasedRenewal]

        Add a policy server application and application pool if necessary.

        This command does not install binaries or packages.

        One of the following authentication methods with which the client connects to a Certificate Policy Server.

        Kerberos : Use Kerberos SSL credentials.

        UserName : Use named account for SSL credentials.

        ClientCertificate : Use X.509 Certificate SSL credentials.

        KeyBasedRenewal : Only policies that contain KeyBasedRenewal templates are returned to the client.

        This flag applies only for UserName and ClientCertificate authentication.

      Delete a Policy Server application

      CertUtil [Options] -deletePolicyServer Kerberos | UserName | ClientCertificate [KeyBasedRenewal]

        Delete a policy server application and application pool if necessary.

        This command does not remove binaries or packages.

        One of the following authentication methods with which the client connects to a Certificate Policy Server.

        Kerberos : Use Kerberos SSL credentials.

        UserName : Use named account for SSL credentials.

        ClientCertificate : Use X.509 Certificate SSL credentials.

        KeyBasedRenewal : KeyBasedRenewal policy server.

      Display ObjectId or set display name

      CertUtil [Options] -oid ObjectId [DisplayName | delete [LanguageId [Type]]] [-f]

      CertUtil [Options] -oid GroupId

      CertUtil [Options] -oid AlgId | AlgorithmName [GroupId] [-f]

        ObjectId : ObjectId to display or to add display name

        GroupId : Decimal GroupId number for ObjectIds to enumerate

        AlgId : Hexadecimal AlgId for ObjectId to look up

        AlgorithmName : Algorithm Name for ObjectId to look up

        DisplayName : Display Name to store in DS

        delete : Delete display name

        LanguageId : Language Id (defaults to current: 1033)

        Type : DS object type to create: 1 for Template (default), 2 for Issuance Policy, 3 for Application Policy

        Use -f to create DS object.

      Display error code message text

      CertUtil [-v] -error ErrorCode

      Display registry value

      CertUtil [Options] -getreg [{ca|restore|policy|exit|template|enroll|chain|PolicyServers}[ProgId]] [RegistryValueName]

        Options: [-f] [-user] [-GroupPolicy] [-config Machine\CAName]

        ca : Use CA's registry key

        restore : Use CA's restore registry key

        policy : Use policy module's registry key

        exit : Use first exit module's registry key

        template : Use template registry key (use -user for user templates)

        enroll : Use enrollment registry key (use -user for user context)

        chain : Use chain configuration registry key

        PolicyServers : Use Policy Servers registry key

        ProgId : Use policy or exit module's ProgId (registry subkey name)

        RegistryValueName : registry value name (use "Name*" to prefix match)

      Set registry value

      CertUtil [Options] -setreg [{ca|restore|policy|exit|template|enroll|chain|PolicyServers}[ProgId]]

         [RegistryValueName] Value

        Options: [-f] [-user] [-GroupPolicy] [-config Machine\CAName]

        ca : Use CA's registry key

        restore : Use CA's restore registry key

        policy : Use policy module's registry key

        exit : Use first exit module's registry key

        template : Use template registry key (use -user for user templates)

        enroll : Use enrollment registry key (use -user for user context)

        chain : Use chain configuration registry key

        PolicyServers : Use Policy Servers registry key

        ProgId : Use policy or exit module's ProgId (registry subkey name)

        RegistryValueName : registry value name (use "Name*" to prefix match)

        Value : new numeric, string or date registry value or filename.

        If a numeric value starts with "+" or "-", the bits specified in the new value are set or cleared in the existing registry value. If a string value

        starts with "+" or "-", and the existing value is a REG_MULTI_SZ value, the string is added to or removed from the existing registry value.

        To force creation of a REG_MULTI_SZ value, add a "\n" to the end of the string value. If the value starts with "@", the rest of the value is the name of the file containing the hexadecimal text representation of a binary value.

        If it does not refer to a valid file, it is instead parsed as [Date][+|-][dd:hh] -- an optional date plus or minus optional days and hours.

        If both are specified, use a plus sign (+) or minus sign (-) separator.

        Use "now+dd:hh" for a date relative to the current time.

        Use "chain\ChainCacheResyncFiletime @now" to effectively flush cached CRLs.

      Delete registry value

      CertUtil [Options] -delreg [{ca|restore|policy|exit|template|enroll|chain|PolicyServers}[ProgId]]

         [RegistryValueName]

        Options: [-f] [-user] [-GroupPolicy] [-config Machine\CAName]

        ca : Use CA's registry key

        restore : Use CA's restore registry key

        policy : Use policy module's registry key

        exit : Use first exit module's registry key

        template : Use template registry key (use -user for user templates)

        enroll : Use enrollment registry key (use -user for user context)

        chain : Use chain configuration registry key

        PolicyServers : Use Policy Servers registry key

        ProgId : Use policy or exit module's ProgId (registry subkey name)

        RegistryValueName : registry value name (use "Name*" to prefix match)

      Import user keys and certificates into server database for key archival

      CertUtil [Options] -ImportKMS UserKeyAndCertFile [CertId]

        Options: [-f] [-v] [-silent] [-split] [-config Machine\CAName] [-p Password] [-symkeyalg SymmetricKeyAlgorithm[,KeyLength]]

        UserKeyAndCertFile : Data file containing user private keys and certificates to be archived.

        This can be any of the following:

           Exchange Key Management Server (KMS) export file

           PFX file

        CertId : KMS export file decryption certificate match token. See -store.

        Use -f to import certificates not issued by the CA.

      Import a certificate file into the database

      CertUtil [Options] -ImportCert Certfile [ExistingRow]

        Options: [-f] [-v] [-config Machine\CAName]

        Use ExistingRow to import the certificate in place of a pending request for the same key.

        Use -f to import certificates not issued by the CA. The CA might also need to be configured to support foreign certificate import: certutil -setreg ca\KRAFlags +KRAF_ENABLEFOREIGN

      Retrieve archived private key recovery blob, generate a recovery script, or recover archived keys

      CertUtil [Options] -GetKey SearchToken [RecoveryBlobOutFile]

      CertUtil [Options] -GetKey SearchToken script OutputScriptFile

      CertUtil [Options] -GetKey SearchToken retrieve | recover OutputFileBaseName

        Options: [-f] [-v] [-UnicodeText] [-silent] [-config Machine\CAName] [-p Password]

                      [-ProtectTo SAMNameAndSIDList] [-csp Provider]

        script : generate a script to retrieve and recover keys (default behavior if multiple matching recovery candidates are found, or if

        the output file is not specified).

        retrieve : retrieve one or more Key Recovery Blobs (default behavior if exactly one

        matching recovery candidate is found, and if the output file is specified)

        recover : retrieve and recover private keys in one step (requires Key Recovery Agent

        certificates and private keys)

        SearchToken : Used to select the keys and certificates to be recovered.

        any of the following:

          Certificate Common Name

          Certificate Serial Number

          Certificate SHA-1 hash (thumbprint)

          Certificate KeyId SHA-1 hash (Subject Key Identifier)

          Requester Name (domain\user)

          UPN (user@domain)

        RecoveryBlobOutFile : output file containing a certificate chain and an associated private key, still encrypted to one or more Key Recovery Agent certificates.

        OutputScriptFile : output file containing a batch script to retrieve and recover private keys.

        OutputFileBaseName : output file base name. For retrieve, any extension is truncated and a certificate-specific string and the .rec extension are appended for each key recovery blob. Each file contains a certificate chain and an associated private key, still encrypted to

        one or more Key Recovery Agent certificates. For recover, any extension is truncated and the .p12 extension is appended.

        Contains the recovered certificate chains and associated private keys, stored as a PFX file.

      Recover archived private key

      CertUtil [Options] -RecoverKey RecoveryBlobInFile [PFXOutFile [RecipientIndex]]

        Options: [-f] [-user] [-silent] [-split] [-p Password] [-ProtectTo SAMNameAndSIDList] [-csp Provider] [-t Timeout]

      Merge PFX files

      CertUtil [Options] -MergePFX PFXInFileList PFXOutFile [ExtendedProperties]

        Options: [-f] [-user] [-split] [-p Password] [-ProtectTo SAMNameAndSIDList] [-csp Provider]

        PFXInFileList : Comma separated PFX input file list

        PFXOutFile : PFX output file

        ExtendedProperties: Include extended properties

        The password specified on the command line is a comma separated password list.

        If more than one password is specified, the last password is used for the output file.

        If only one password is provided or if the last password is "*", the user will be prompted for

        the output file password.

      Convert PFX files to EPF file

      CertUtil [Options] -ConvertEPF PFXInFileList EPFOutFile [cast | cast-] [V3CACertId][,Salt]

        Options: [-f] [-split] [-p Password] [-csp Provider]

        PFXInFileList : Comma separated PFX input file list

        EPF : EPF output file

        cast : Use CAST 64 encryption

        cast- : Use CAST 64 encryption (export)

        V3CACertId : V3 CA Certificate match token. See -store CertId description.

        Salt: EPF output file salt string

        The password specified on the command line is a comma separated password list.

        If more than one password is specified, the last password is used for the output file.

        If only one password is provided or if the last password is "*", the user will be prompted for

        the output file password.

    OPTIONS

    These options must be entered on the command line before the main Verb

       -nullsign Use hash of data as signature

       -f Force overwrite

       -enterprise Use local machine Enterprise registry certificate store

       -user Use HKEY_CURRENT_USER keys or certificate store

       -GroupPolicy Use Group Policy certificate store

       -ut Display user templates

       -mt Display machine templates

       -Unicode Write redirected output in Unicode

       -UnicodeText Write output file in Unicode

       -gmt Display times as GMT

       -seconds Display times with seconds and milliseconds

       -silent Use silent flag to acquire crypt context

       -split Split embedded ASN.1 elements, and save to files

       -v Verbose operation

       -privatekey Display password and private key data

       -pin PIN Smart Card PIN

       -urlfetch Retrieve and verify AIA Certs and CDP CRLs

       -config Machine\CAName CA and computer name string

       -PolicyServer URLOrId Policy Server URL or Id. For selection U/I, use -PolicyServer.

                               For all Policy Servers, use -PolicyServer *

       -Anonymous Use anonymous SSL credentials

       -Kerberos Use Kerberos SSL credentials

       -ClientCertificate ClientCertId Use X.509 Certificate SSL credentials. For selection U/I, use -clientCertificate.

       -UserName UserName Use named account for SSL credentials. For selection U/I, use -UserName.

       -Cert CertId Signing certificate

       -dc DCName Target a specific Domain Controller

       -restrict RestrictionList Comma separated Restriction List. Each restriction consists

                     of a column name, a relational operator and a constant integer, string or date.

                     One column name can be preceded by a plus or minus sign to indicate the sort order.

                     Examples: "RequestId = 47" "+RequesterName >= a, RequesterName < b"

                                "-RequesterName > DOMAIN, Disposition = 21"

       -out ColumnList Comma separated Column List

       -p Password Password

       -ProtectTo SAMNameAndSIDList Comma separated SAM Name/SID List

       -csp Provider Provider

       -t Timeout URL fetch timeout in milliseconds

       -symkeyalg SymmetricKeyAlgorithm[,KeyLength] Name of Symmetric Key Algorithm with

                     optional key length, example: AES,128 or 3DES

    Certutil is sensitive to the order of command-line parameters.

    Certutil replaces the File Checksum Integrity Verifier (FCIV) found in earlier versions of Windows.

    There are a some documentation inconsistencies between the command-line help (Certutil -?) and the various MSDN help pages.

    e.g. -encodehex is completely missing from the command-line help.

    The -decode option might not always restore spaces - see forum thread.

    Examples

    Display the SHA256 hash of a file:

    certutil -hashfile c:\demo\anything.txt SHA256

    Dump (read config information) from a certificate file:

    certutil -dump c:\demo\sample.CER

    Copy a certificate revocation list (CRL) to a file:

    certutil -getcrl F:\ss64.crl

    Purge local policy cache (Certificate Enrollment Policy Web Services):

    certutil -f -policyserver * -policycache delete

    View the content of the client computer’s Trusted Root Certification Authorities Enterprise certificate store:

    certutil -enterprise -viewstore Root

    Check the browsers Trusted Certificate list against the WindowsUpdate servers:

    certutil -f -verifyCTL AuthRootWU

    Stop Certificate Services:

    certutil -shutdown

    Convert a hex-encoded file to a binary executable. This is primarily intended for converting X.509 certificates from a human-readable format (.asn) into a computer-readable format (.bin):

    certutil -decodehex hex.dat ss64.exe

    vector】 Vectors are sequence containers representing arrays that can change in size【cpp】


    Library to include

    include

    vector a; Declare an empty vector, a.

    a.push_back(1); Appends/Adds an element whose value is 1 to vector a.

    std::cout << a.at(0) << std::endl; Accessing index 0 of vector a.

    a.size(); Returns the size of the vector

    a.at(0) = 420; Changing the value at index 0 to 420.

    ControlFlow】 【rust】


    for loops/iteration

    let array = [1, 2, 3];

    for i in array.iter() {

        println!("{}", i);

    }

    Ranges

    for i in 0u32..10 {

        print!("{} ", i);

    }

    println!("");

    prints `0 1 2 3 4 5 6 7 8 9 `

    if

    if 1 == 1 {

        println!("Maths is working!");

    } else {

        println!("Oh no...");

    }

    if as expression

    let value = if true {

        "good"

    } else {

        "bad"

    };

    while loop

    while 1 == 1 {

        println!("The universe is operating normally.");

    }

    Infinite loop

    loop {

        println!("Hello!");

    }

    cpp】 【cpp】


    C++ is an object-oriented programming language which provides facilities for low-level memory manipulation.

    It is widely used by big tech companies, such as, Amazon, Facebook, Google, and SpaceX

    To Compile: g++ my_script.cpp

    To Execute: ./a.out

    connection】 【redis】


    Authenticate to the server

    AUTH password

    Echo the given string

    ECHO message

    Ping the server

    PING [message]

    Close the connection

    QUIT

    Change the selected database for the current connection

    SELECT index

    Swaps two Redis databases

    SWAPDB index index

    journalctl】 【linux】


    Actively follow log (like tail -f)

    journalctl -f

    Display all errors since last boot

    journalctl -b -p err

    Filter by time period

    journalctl --since=2012-10-15 --until="2011-10-16 23:59:59"

    Show list of systemd units logged in journal

    journalctl -F _SYSTEMD_UNIT

    Filter by specific unit

    journalctl -u dbus

    Filter by executable name

    journalctl /usr/bin/dbus-daemon

    Filter by PID

    journalctl _PID=123

    Filter by Command, e.g., sshd

    journalctl _COMM=sshd

    Filter by Command and time period

    journalctl _COMM=crond --since '10:00' --until '11:00'

    List all available boots

    journalctl --list-boots

    Filter by specific User ID e.g., user id 1000

    journalctl _UID=1000

    COREINFO】 Show the mapping between logical processors and the physical processor, NUMA node, and socket on which they reside.【win】


    Syntax

          coreinfo [-c][-f][-g][-l][-n][-s][-m][-v] -c

    Key:

       -c Dump information on cores.

       -f Dump core feature information.

       -g Dump information on groups.

       -l Dump information on caches.

       -n Dump information on NUMA nodes.

       -s Dump information on sockets.

       -m Dump NUMA access cost.

       -v Dump only virtualization-related features including support

            for second level address translation.

            (requires administrative rights on Intel systems).

    All options except -v are selected by default.

    Examples

    Drop all the coreinfo data into a text file:

    coreinfo.exe > coreinfo.txt

    change】 Change Terminal Server Session properties, use when installing software on a terminal server.【win】


    Syntax

          CHANGE USER /options

          CHANGE LOGON /options

          CHANGE PORT /options

    Options:

      To change .INI file mapping: (administrator rights required)

      CHANGE USER /INSTALL Enable install mode. This command has to be run before

                             installing any new software on a Terminal Server.

                             This will create a .ini file for the application

                             in the TS system directory.

      CHANGE USER /EXECUTE Enable execute mode (default)

                             Run this when an installation is complete.

      CHANGE USER /QUERY Display current settings.

      To enable or disable terminal session logins:

      CHANGE LOGON /QUERY Query current terminal session login mode.

      CHANGE LOGON /ENABLE Enable user login from terminal sessions.

      CHANGE LOGON /DISABLE Disable user login from terminal sessions.

      To list or change COM port mappings for the current session.

      This can allow DOS applications to access high numbered ports e.g. COM12

      CHANGE PORT portx=porty Map port x to port y.

      CHANGE PORT /D portx Delete mapping for port x.

      CHANGE PORT /QUERY Display current mapping ports.

    How .ini files work:

    Installing an application will create a .ini file in the TS system directory.

    The first time a user runs the application, the application looks in the home directory for its .ini file. If none is found then Terminal Server will copy the .ini file from the system directory to the users home directory.

    Each user will have a unique copy of the application's .ini file in their home directory.

    To learn more about what happens when the system is put into install mode run CHANGE USER /?

    The CHANGE command replaces CHGLOGON, CHGUSER, and CHGPORT from Citrix Winframe.

    gcc】 Compile tool【linux】


    Compile a file

    gcc file.c

    Compile a file with a custom output

    gcc -o file file.c

    Debug symbols

    gcc -g

    Debug with all symbols.

    gcc -ggdb3

    Build for 64 bytes

    gcc -m64

    Include the directory {/usr/include/myPersonnal/lib/} to the list of path for #include <....>

    With this option, no warning / error will be reported for the files in {/usr/include/myPersonnal/lib/}

    gcc -isystem /usr/include/myPersonnal/lib/

    Build a GUI for windows (Mingw) (Will disable the term/console)

    gcc -mwindows

    certreq】 【win】


    Request certificate from a certification authority (CA), retrieve a response to a previous request from a CA, create a new request from an .inf file, accept and install a response to a request, construct a cross-certification or qualified subordination request from an existing CA certificate or request, or to sign a cross-certification or qualified subordination request.

    Syntax

          Certreq [-submit] [-retrieve RequestID] [-new] [-accept] [-policy] [-sign]

                     [-attrib AttributeString] [-binary] [-config CAMachineName\CAName]

                        [-crl] [-rpc] [-cert CertID]

                           [RequestFileIn | CertChainFileIn | FullResponseFileIn | CertFileIn | PolicyFileIn]

                              [RequestFileOut | CertChainFileOut | FullResponseFileOut | CertFileOut | PKCS10FileOut]

    Key

       -submit

              Submit a request to a CA.

       -retrieve RequestID

              Retrieve a response to a previous request from a CA.

       -new

              Create a new request from an .inf file.

       -accept

              Accept and install a response to a certificate request.

       -policy

              Set the policy for a request.

       -sign

              Sign a cross-certification or qualified subordination request.

       -attrib AttributeString

              The Name and Value string pairs, separated by a colon.

              Separate Name and Value string pairs with \n (for example, Name1:Value1\nName2:Value2).

       -binary

              Format output files as binary instead of base64-encoded.

       -config CAMachineName\CAName

              Process the operation using the CA specified in the configuration

              string, which is CAMachineName\CAName.

       -crl

              Include certificate revocation lists (CRLs) in the output to the base64-encoded

              PKCS #7 file specified by CertChainFileOut or to the base64-encoded file

              specified by RequestFileOut.

       -rpc

              Instructs Active Directory Certificate Services (AD CS) to use a

              remote procedure call (RPC) server connection instead of Distributed COM.

       -cert CertID

              The signing certificate by common name, serial number, Secure Hash Algorithm

              (SHA-1) key, or certificate hash.

       CertChainFileIn

              The base64-encoded or binary certificate chain input file to use.

       FullResponseFileIn

              The base64-encoded or binary full response input file to use.

       CertFileIn

              The base64-encoded or binary certificate input file to use.

       RequestFileIn

              The base64-encoded or binary input file to use.

              The file can be a PKCS #10 certificate request, a PKCS #7 certificate renewal

              request, a KEYGEN tag format certificate request, a Certificate Management protocol

              using Cryptographic Message Syntax (CMS) request (this protocol is also known as CMC),

              or a certificate file of the CA that you want to cross-certify.

       PolicyFileIn

              The .inf input file that contains the extension definitions to use to qualify a request.

       RequestFileOut

              The base64-encoded file to which you want to send output.

       PKCS10FileOut

              The base64-encoded PKCS #10 file to which you want to send output.

       CertFileOut

              The binary or base64-encoded X.509 v3 file to which you want to send output.

       CertChainFileOut

              The binary or base64-encoded PKCS #7 file to which you want to send output.

       FullResponseFileOut

              The binary or base64-encoded full response file to which you want to send output.

       -? Display a list of certreq commands.

    You must specify the CAComputerName or CAName in -config CAComputerName\CAName. Otherwise, the Select Certificate Authority dialog box appears and displays a list of all CAs that are available.

    To retrieve the certificate after the CA has actually issued it use certreq -retrieve RequestID, you can also use this command to retrieve any certificate that has ever been issued by the CA, including revoked or expired certificates, without regard to whether the certificate's request was ever in the pending state.

    If you submit a request to the CA, the policy module of the CA might temporarily leave the request in a pending state and return the RequestID for display. Eventually, the CA’s administrator will issue the certificate or deny the request.

    Examples

    Sample request.inf

    ;----------------- request.inf

    [Version]

    Signature="$Windows NT$

    [NewRequest]

    Subject = "CN=dc01.ss64.com" ; must be the FQDN of domain controller

    ;EncipherOnly = FALSE

    Exportable = FALSE ; TRUE = Private key is exportable

    KeyLength = 1024 ; Common key sizes: 512, 1024, 2048,

    ; 4096, 8192, 16384

    KeySpec = 1 ; Key Exchange

    KeyUsage = 0xA0 ; Digital Signature, Key Encipherment

    MachineKeySet = True

    ProviderName = "Microsoft RSA SChannel Cryptographic Provider"

    ProviderType = 12

    RequestType = CMC

    ; Omit entire section if CA is an enterprise CA

    [EnhancedKeyUsageExtension]

    OID=1.3.6.1.5.5.7.3.1 ; Server Authentication

    [RequestAttributes]

    CertificateTemplate = WebServer ;Omit line if CA is a stand-alone CA

    ;SAN="dns=dc01.ss64.com&dns=.ss64.com&dns=ldap.ss64.com"

    ;-----------------

    Create a new request from an .inf file:

    certreq -new request.inf result.txt

    Supply the text of result.txt to your CA to obtain a signed certificate (and an intermediate CA certificate, if applicable.)

    Submit a request to a CA:

    certreq -submit result.txt certificate.cer

    Retrieve a response to a previous request from a CA:

    certreq -retrieve [-binary] [-config CAMachineName\CAName] [-crl] [-rpc] RequestID [CertFileOut [CertChainFileOut [FullResponseFileOut]]]

    Accept and install a response to a certificate request:

    certreq -accept c:\certificates\certificate.cer

    Construct a cross-certification or qualified subordination request from an existing CA certificate or request:

    certreq -policy [-attrib AttributeString] [-binary] [-cert CertID] [RequestFileIn [PolicyFileIn [RequestFileOut [PKCS10FileOut]]]]

    Sign a cross-certification or qualified subordination request:

    certreq -sign [-binary] [-certCertID] [-crl] [RequestFileIn [RequestFileOut]]

    setup-apkcache】 【linux】


    apk is the tool used to install, upgrade, or delete software on a running system

    of Alpine Linux package management

    To enable local APK cache run

    setup-apkcache

    If you've installed Alpine to your hard drive (as 'sys'),

    then create a cache dir and then an /etc/apk/cache symlink pointing to that dir:

    mkdir -p /var/cache/apk

    ln -s /var/cache/apk /etc/apk/cache

    DSACLS】 View or Edit ACLs (access control entries) for objects in Active Directory.【win】


    Syntax

          DSACLS "[\Computer]ObjectDN" [/A] [/D PermissionStatement [PermissionStatement]...]

             [/G PermissionStatement [PermissionStatement]...] [/I:{T | S | P}]

                [/N] [/P:{Y | N}]

                   [/R {User | Group} [{User | Group}]...] [/S [/T]]

          PermissionStatements:

             {User | Group}:Permissions[;{ObjectType | Property}][;InheritedObjectType]

    Key

       ObjectDN Distinguished name of the object.

                 If omitted will be taken from standard input (stdin)

       /A Add ownership and auditing information to the results.

       /D Deny permissions to a user or group

       /G Grant permissions to a user or group.

       /I: Inheritance

               T The object and its child objects (default)

               S The child objects only

               P The object and child objects down one level only

       /N Replace the current ACEs in the ACL.

            By default, dsacls adds the ACE to the ACL.

       /P: Inherit permissions from parent objects (Y/N).

       /R Revoke/Delete all ACEs for the users or groups.

       /S Restore the default security.

            Default security for each object class is defined in the Active Directory schema.

      /S /T Restore the default security on the tree of objects.

    Permissions

          GR: Generic Read

          GE: Generic Execute

          GW: Generic Write

          GA: Generic All

          SD: Delete an object

          DT: Delete an object and all of its child objects

          RC: Read security information

          WD: Change security information

          WO: Change owner information

          LC: List the child objects of the object

          CC: Create a child object•

          DC: Delete a child object•

          WS: Write to a self object (group membership) group object + {ObjectType | Property} = "member."

          RP: Read a property•

          WP: Write to a property•

          CA: Control access (normally a specific extended right for control access)

                 If you do not specify {ObjectType | Property} this permission will apply to all

                 meaningful control accesses on the object.

          LO: List the object access, AD DS does not enforce this permission by default.

                 Grant list access to a specific object when List Children (LC) is not granted to the parent.

                 Deny list access to a specific object when the user or group has LC permission on the parent.

       ObjectType | Property

              Limit the permission to the specified object type or property.

              Enter the display name of the object type or the property.

              Default=all object types and properties.

              For example, Grant the user rights to create all types of child objects:

              /G Domain\User:CC

              Grant the user rights to create only child computer objects:

              /G Domain\User:CC;computer

       InheritedObjectType

              Limit inheritance of the permission to the specified object type.

              For example, Grant only User objects to inherit the permission:

              /G Domain\User:CC;;user

       Object Types

              User,Contact,Group,Shared Folder,Printer,Computer,Domain Controllers,OU

    • If you do not specify {ObjectType | Property} to define a specific child object type, this permission will apply to all types of child objects; otherwise, it will apply only to the child object type that you specify.

    You can Grant, Deny or Delete ACEs for multiple users and groups with a single parameter (/G /D /R), list the users/groups separated with spaces.

    Examples

    Grant Generic Read (GR) and Generic Execute (GE) on computer objects in the Laptops OU to Jdoe:

    C:\> dsacls "OU=Laptops,OU=AcmeCo,DC=ss64,DC=Com" /G Domain\JDoe:GRGE;computer

    ncmpcpp】 an mpd client【linux】


    ncmpcpp is an mpd client (compatible with mopidy) with a UI very similar to ncmpc,

    but it provides new useful features such as support for regular expressions for library searches,

    extended song format, items filtering, the ability to sort playlists, and a local filesystem browser.

    configure ncmpcpp

    mkdir ~/.ncmpcpp

    cat < ~/.ncmpcpp/config

    ncmpcpp_directory = "~/.ncmpcpp"

    mpd_host = "127.0.0.1"

    mpd_port = "6600"

    mpd_music_dir = "/var/lib/mpd/music/"

    EOF

    Movement

        Up k Move cursor up

        Down j Move cursor down

        [ Move cursor up one album

        ] Move cursor down one album

        { Move cursor up one artist

        } Move cursor down one artist

        Page Up Page up

        Page Down Page down

        Home Home

        End End

        Tab Switch to next screen in sequence

        Shift-Tab Switch to previous screen in sequence

        F1 Show help

        1 Show playlist

        2 Show browser

        3 Show search engine

        4 Show media library

        5 Show playlist editor

        6 Show tag editor

        7 Show outputs

        8 Show music visualizer

        = Show clock

        @ Show server info

    Global

        s Stop

        p Pause

    Next track Previous track

        Ctrl-H Backspace Replay playing song

        f Seek forward in playing song

        b Seek backward in playing song

        - Left Decrease volume by 2%

        Right + Increase volume by 2%

        t Toggle space mode (select/add)

        T Toggle add mode (add or remove/always add)

        | Toggle mouse support

        v Reverse selection

        V Remove selection

        B Select songs of album around the cursor

        a Add selected items to playlist

         Add random items to playlist

        r Toggle repeat mode

        z Toggle random mode

        y Toggle single mode

        R Toggle consume mode

        Y Toggle replay gain mode

    Toggle bitrate visibility

        Z Shuffle playlist

        x Toggle crossfade mode

        X Set crossfade

        u Start music database update

        : Execute command

        Ctrl-F Apply filter

        / Find item forward

        ? Find item backward

        , Jump to previous found item

        . Jump to next found item

        w Toggle find mode (normal/wrapped)

        G Locate song in browser

        ~ Locate song in media library

        Ctrl-L Lock/unlock current screen

        Left h Switch to master screen (left one)

        Right l Switch to slave screen (right one)

        E Locate song in tag editor

        P Toggle display mode

        \ Toggle user interface

        ! Toggle displaying separators between albums

        g Jump to given position in playing song (formats: mm:ss, x%)

        i Show song info

        I Show artist info

        L Toggle lyrics fetcher

        F Toggle fetching lyrics for playing songs in background

        q Quit

    Playlist

        Enter Play selected item

        Delete Delete selected item(s) from playlist

        c Clear playlist

        C Clear playlist except selected item(s)

        Ctrl-P Set priority of selected items

        Ctrl-K m Move selected item(s) up

        n Ctrl-J Move selected item(s) down

        M Move selected item(s) to cursor position

        A Add item to playlist

        e Edit song

        S Save playlist

        Ctrl-V Sort playlist

        Ctrl-R Reverse playlist

        o Jump to current song

        U Toggle playing song centering

    Browser

        Enter Enter directory/Add item to playlist and play it

        Space Add item to playlist/select it

        e Edit song/directory/playlist name

        2 Browse MPD database/local filesystem

         Toggle sort mode

        o Locate playing song

        Ctrl-H Backspace Jump to parent directory

        Delete Delete selected items from disk

        G Jump to playlist editor (playlists only)

    Search engine

        Enter Add item to playlist and play it/change option

        Space Add item to playlist

        e Edit song

        y Start searching

        3 Reset search constraints and clear results

    Media library

        4 Switch between two/three columns mode

        Left h Previous column

        Right l Next column

        Enter Add item to playlist and play it

        Space Add item to playlist

        e Edit song

        e Edit tag (left column)/album (middle/right column)

         Toggle type of tag used in left column

        m Toggle sort mode

    Playlist editor

        Left h Previous column

        Right l Next column

        Enter Add item to playlist and play it

        Space Add item to playlist/select it

        e Edit song/playlist name

        Ctrl-K m Move selected item(s) up

        n Ctrl-J Move selected item(s) down

        Delete Delete selected playlists (left column)

        C Clear playlist except selected item(s)

        Ctrl-P Set priority of selected items

        Ctrl-K m Move selected item(s) up

        n Ctrl-J Move selected item(s) down

        M Move selected item(s) to cursor position

        A Add item to playlist

        e Edit song

        S Save playlist

        Ctrl-V Sort playlist

        Ctrl-R Reverse playlist

        o Jump to current song

        U Toggle playing song centering

    Browser

        Enter Enter directory/Add item to playlist and play it

        Space Add item to playlist/select it

        e Edit song

        e Edit directory name

        e Edit playlist name

        2 Browse MPD database/local filesystem

         Toggle sort mode

        o Locate playing song

        Ctrl-H Backspace Jump to parent directory

        Delete Delete selected items from disk

        G Jump to playlist editor (playlists only)

    Search engine

        Enter Add item to playlist and play it/change option

        Space Add item to playlist

        e Edit song

        y Start searching

        3 Reset search constraints and clear results

    Media library

        4 Switch between two/three columns mode

        Left h Previous column

        Right l Next column

        Enter Add item to playlist and play it

        Space Add item to playlist

        e Edit song/tag (left column)/album (middle/right column)

         Toggle type of tag used in left column

        m Toggle sort mode

    Playlist editor

        Left h Previous column

        Right l Next column

        Enter Add item to playlist and play it

        Space Add item to playlist/select it

        e Edit song/playlist name

        Ctrl-K m Move selected item(s) up

        n Ctrl-J Move selected item(s) down

        Delete Delete selected playlists (left column)

        Delete Delete selected item(s) from playlist (right column)

        c Clear playlist

        C Clear playlist except selected items

    Lyrics

        Space Toggle reloading lyrics upon song change

        e Open lyrics in external editor

         Refetch lyrics

    Tiny tag editor

        Enter Edit tag

        y Save

    Tag editor

        Enter Edit tag/filename of selected item (left column)

        Enter Perform operation on all/selected items (middle column)

        Space Switch to albums/directories view (left column)

        Space Select item (right column)

        Left h Previous column

        Right l Next column

        Ctrl-H Backspace Jump to parent directory (left column, directories view)

    cloudup】 【linux】


    cloudup (Bash-Snippets)

    Backs up a users github repositories to your bitbucket account.

    Backup all of a single github users repositories

    cloudup -a

    Backup a single github repository

    cloudup

    Backup a single github repository (supplying the name of repo as argument)

    cloudup repositoryName

    crud】 【mongo】


    Insert a new document in a collection

    db.books.insert({"isbn": 9780060859749, "title": "After Alice: A Novel", "author": "Gregory Maguire", "category": "Fiction", "year":2016})

    Insert multiple documents into a collection

    db.books.insert([

        { "isbn":"9781853260001", "title": "Pride and Prejudice", "author": "Jane Austen", "category": "Fiction"},

        {"isbn": "9780743273565", "title": "The Great Gatsby", "author": "F. Scott Fitzgerald"}

        ])

    Show all documents in the collection

    db.collection.find()

    Filter documents by field value condition

    db.books.find({"title":"Treasure Island"})

    Show only some fields of matching documents

    db.books.find({"title":"Treasure Island"}, {title:true, category:true, _id:false})

    Show the first document that matches the query condition

    db.books.findOne({}, {_id:false})

    Update specific fields of a single document that match the query condition

    db.books.update({title : "Treasure Island"}, {$set : {category :"Adventure Fiction"}})

    Remove certain fields of a single document the query condition:

    $unset

    db.books.update({title : "Treasure Island"}, {$unset : {category:""}})

    Remove certain fields of all documents that match the query condition

    $unset, {multi:true}

    db.books.update({category : "Fiction"}, {$unset : {category:""}}, {multi:true})

    Delete a single document that match the query condition

    {justOne:true}

    db.books.remove({title :"Treasure Island"}, {justOne:true})

    Delete all documents matching a query condition

    db.books.remove({"category" :"Fiction"})

    Delete all documents in a collection

    db.books.remove({})

    Drop a collection

    db.books.drop()

    cat】 displaying the file content【linux】


    Display the contents of a file

    cat /path/to/foo

    Display contents with line numbers

    cat -n /path/to/foo

    Display contents with line numbers (blank lines excluded)

    cat -b /path/to/foo

    stocks】 Finds the latest information on a certain stock【linux】


    Determine the latest stock information searching by company

    stocks Tesla

    Determine the latest stock information searching by stock ticker

    stocks AAPL

    CON】 CON (short for Console) is an input/output DEVICE, not a command.【win】


    Syntax

       Copy from the console to a new file:

          COPY CON filename.txt

       Type from the console to a new file:

          TYPE CON > Newfile.txt

       Type from the console to overwrite a file:

          TYPE CON >> Newfile.txt

       Copy a file to the console:

          COPY file.txt CON

       The console accepts this input and acts like TYPE file.txt

       Pass an Echo command as input to the console:

          Echo some text >CON

       Without context this may not look useful, but when used within a redirected block,

       it allows one line to break out of the redirection and display on the screen:

      (

       Echo Start

       Echo Something happened >CON

       Echo end of demo

      ) >logfile.txt

    After entering COPY CON or TYPE CON, type in the text required, note there is no prompt for this, then end the file by typing CTRL-Z, this will insert an EOF marker: ASCII 0x1a (SUB).

    When using COPY the CTRL-Z can be placed anywhere, but when using TYPE it is important that the CTRL-Z is only entered at the beginning of a new line, otherwise it will just be saved into the file and you will have two EOF markers in the same file.

    Most basic text editors will stop reading after the first EOF marker.

    Some commands e.g. CLS, do not work as expected when redirected to CON and will output extra control characters.

    To read text from the console in PowerShell use the following function:

    function copycon {

    [system.console]::in.readtoend()

    }

    con is a reserved filename.

    A more advanced use of the console device is to redirect the console CON into FIND and then redirect the output from FIND into a file, this will make FIND discard any lines which do not contain the desired text. This can be useful for condensing large log files to return only the lines of interest.

    Example:

    C:\> FIND /i "Jones" logfile.txt

    asdf

    asdf

    zz Jones 2

    asdf

    ^Z

    C:\> TYPE logfile.txt

    zz Jones 2

    lvcreate】 Creates a logical volume in an existing volume group.【linux】


    Create a logical volume of 10 gigabytes in the volume group vg1:

    lvcreate -L 10G vg1

    Create a 1500 megabyte linear logical volume named mylv in the volume group vg1:

    lvcreate -L 1500 -n mylv vg1

    Create a logical volume called mylv that uses 60% of the total space in volume group vg1:

    lvcreate -l 60%VG -n mylv vg1

    Create a logical volume called mylv that uses all of the unallocated space in the volume group vg1:

    lvcreate -l 100%FREE -n mylv vg1

    Create a snapshot (lvsnap) from a logical volume (/dev/vgA/lv1);

    snapshot size = 10G (total size of the changes)

    lvcreate -L 10G -s -n lvsnap /dev/vgA/lv1

    Clone LVM volume: test => testCopy

    lvconvert --type mirror --alloc anywhere -m1 /dev/mylv/test

    lvs -a -o +devices | egrep "LV|test"

    After Cpy%Sync is 100% finished:

    lvconvert --splitmirrors 1 --name testCopy /dev/rootvg/test

    Recursion】 【linux】


    Recursion

    Def: "...is a method where the solution to a problem depends on solutions to smaller instance of the same problem.." - wiki

    TL;DR: a function that calls itself inside its body.

    Recursive programs - Pseduocode

    function factorial:

    input: integer n such that n >= 0

    output: n * (n-1) * (n-2) * ... * 1 = n!

    1. if n is 0, return 1
    2. else, return ( n * factorial(n-1) )

    comp】 Compare two files (or sets of files). Display items which do not match.【win】


    Syntax

          COMP [pathname1] [pathname2] [/D] [/A] [/L] [/N=number] [/C]

    Key

       pathname1 The path and filename of the first file(s)

       pathname2 The path and filename of the second file(s)

       /D Display differences in decimal format. (default)

       /A Display differences in ASCII characters.

       /L Display line numbers for differences.

       /N=number Compare only the first number of lines in the file.

       /C Do a Case insensitive string comparison

    Running COMP with no parameters will result in a prompt for the 2 files and any options

    To compare sets of files, use wildcards in pathname1 and pathname2 parameters.

    When used with the /A option COMP is similar to the FC command but it displays the individual characters that differ between the files rather than the whole line.

    To compare files of different sizes, use /N= to compare only the first n lines (common portion of each file.)

    COMP will normally finish with a Compare more files (Y/N) prompt,

    to suppress this: ECHO n|COMP

    Errorlevel

    COMP will return an ErrorLevel as follows:

        0 Files are identical

        1 Files are different

        2 Cannot open one of the files or invalid arguments or invalid switch

    copy】 Copy one or more files to another location.【win】


    Syntax

          COPY [options] [/A|/B] source [/A|/B] [+ source2 [/A|/B]...] [destination [/A|/B]]

          COPY source1 + source2.. destination [options]

    Key

       source Pathname for the file or files to be copied.

       /A ASCII text file (default)

       /B Binary file copy - will copy extended characters.

       /D Allow the destination file to be created decrypted.

       destination Pathname for the new file(s).

       /V Verify that the destination file, once written, can be read.

            No comparison with the source files occurs.

       /N If at all possible, create only short filenames (8.3) in the destination.

            This option can help when copying between disks that are formatted differently

            e.g NTFS and VFAT, or when archiving data to an ISO9660 CDROM.

       /L If source is a symbolic link copy the link to the target

            instead of the actual file the source link points to.

       /Y Suppress confirmation prompt, when overwriting files.

       /-Y Enable confirmation prompt, when overwriting files.

       /Z Copy files in restartable mode. If the copy is interrupted part way through,

            it will restart if possible. Also displays a '% complete' which counts up to 100%.

       /? Display help.

    Combining files

        To combine files, specify a single file for the destination, but multiple files as the source. To specify more than one file use wildcards or list the files with a + in between each (file1+file2+file3).

        When copying multiple files in this way the first file must exist or else the copy will fail, a workaround for this is COPY null + file1 + file2 dest1

    Binary copies

        "COPY /B ... " will copy files in binary mode.

        The /A and /B options can appear in multiple locations, with different meanings depending on location.

        Before any source - they will set the default mode for all source and destination files.

        After a source - they will set the mode for that source.

        After the destination - they will set the mode for the destination.

    Copy from the console (accept user input)

        COPY CON filename.txt

        Then type the input text followed by ^Z (Control key & Z)

    Prompt to overwrite destination file

        Under Windows 2000 and above, the default action is to prompt on overwrite unless the command is being executed from within a batch script.

        To force the overwriting of destination files use the COPYCMD environment variable:

        SET COPYCMD=/Y

    Errorlevels

        If the file(s) were successfully copied %ERRORLEVEL% = 0

        If the file was not found or bad parameters given = 1

    COPY will accept UNC pathnames.

    COPY is an internal command.

    Examples:

    Copy a file in the current folder

    COPY source_file.doc newfile.doc

    Copy from a different folder/directory:

    COPY "C:\my work\some file.doc" "D:\New docs\newfile.doc"

    Specify the source only, with a wildcard will copy all the files into the current directory:

    COPY "C:\my work*.doc"

    Specify the source with a wildcard and the destination as a single file, this is generally only useful with plain text files.

    COPY "C:\my work*.txt" "D:\New docs\combined.txt"

    Create an empty (zero byte) file:

    COPY NUL EmptyFile.txt

    Quiet copy (no feedback on screen)

    COPY source_file.doc newfile.doc >nul

    Copy a file, but do not overwrite if the destination file already exists, this technique only works for a single file, no wildcards:

    Echo n|COPY /-y c:\demo\source_file.txt c:\dir\dest.txt

    smartctl】 get SMART status information on your hard drives【linux】


    Quickly check the overall health of a drive

    smartctl -H /dev/sda

    Obtain information on the drive: view the type of drive, its serial number, and so forth

    smartctl -i /dev/sda

    initiate short tests for the drive

    smartctl --test=short /dev/sda

    initiate long tests for the drive

    smartctl --test=long /dev/sda

    abort the test

    smartctl -X

    change】 Change Terminal Server Session properties, use when installing software on a terminal server. 【win】


    Syntax

          CHANGE USER /options

          CHANGE LOGON /options

          CHANGE PORT /options

    Options:

      To change .INI file mapping: (administrator rights required)

      CHANGE USER /INSTALL Enable install mode. This command has to be run before

                             installing any new software on a Terminal Server.

                             This will create a .ini file for the application

                             in the TS system directory.

      CHANGE USER /EXECUTE Enable execute mode (default)

                             Run this when an installation is complete.

      CHANGE USER /QUERY Display current settings.

      To enable or disable terminal session logins:

      CHANGE LOGON /QUERY Query current terminal session login mode.

      CHANGE LOGON /ENABLE Enable user login from terminal sessions.

      CHANGE LOGON /DISABLE Disable user login from terminal sessions.

      To list or change COM port mappings for the current session.

      This can allow DOS applications to access high numbered ports e.g. COM12

      CHANGE PORT portx=porty Map port x to port y.

      CHANGE PORT /D portx Delete mapping for port x.

      CHANGE PORT /QUERY Display current mapping ports.

    How .ini files work:

    Installing an application will create a .ini file in the TS system directory.

    The first time a user runs the application, the application looks in the home directory for its .ini file. If none is found then Terminal Server will copy the .ini file from the system directory to the users home directory.

    Each user will have a unique copy of the application's .ini file in their home directory.

    To learn more about what happens when the system is put into install mode run CHANGE USER /?

    The CHANGE command replaces CHGLOGON, CHGUSER, and CHGPORT from Citrix Winframe.

    masscan】 【linux】


    Usage is similar to nmap. To scan a network segment for some ports

    masscan -p80,8000-8100 10.0.0.0/8

    scan the entire Internet excluding exclude.txt

    masscan 0.0.0.0/0 -p0-65535 --excludefile exclude.txt --max-rate 100000

    chcp】 Change the active console Code Page.【win】


    Syntax

          CHCP code_page

    Key

       code_page A code page number (e.g. 437)

    This command is rarely required as most GUI programs and PowerShell now support Unicode. When working with characters outside the ASCII range of 0-127, the choice of code page will determine the set of characters displayed.

    Programs that you start after you assign a new code page will use the new code page, however, programs (except Cmd.exe) that you started before assigning the new code page will use the original code page.

    Code page Country/ Region/ Language

    437 United States default code page in the US

    850 Multilingual (Latin I) default code page in most of Europe

    852 Slavic (Latin II)

    855 Cyrillic (Russian)

    857 Turkish

    860 Portuguese

    861 Icelandic

    863 Canadian-French

    865 Nordic

    866 Russian

    869 Modern Greek

    1252 West European Latin

    65000 UTF-7 *

    65001 UTF-8 *

    Even if you use CHCP to run the Windows Console in a unicode code page, many applications will assume that the default still applies, e.g. Java requires the-Dfile option: java -Dfile.encoding=UTF-8

    Unicode characters will only display if the current console font contains the characters. So use a TrueType font like Lucida Console instead of the CMD default Raster Font.

    The CMD Shell (which runs inside the Windows Console)

        CMD.exe only supports two character encodings Ascii and Unicode (CMD /A and CMD /U)

        If you need full unicode support use PowerShell. There is still VERY limited support for unicode in the CMD shell, piping, redirection and most commands are still ANSI only. The only commands that work are DIR, FOR /F and TYPE, this allows reading and writing (UTF-16LE / BOM) files and filenames but not much else.

    Code Pages

        The number of supported code pages was greatly increased in Windows 7.

        For a full list of code pages supported on your machine, run NLSINFO (Resource Kit Tools).

        Files saved in Windows Notepad will be in ANSI format by default, but can also be saved as Unicode UTF-16LE or UTF -8 and for unicode files, will include a BOM.

        A BOM will make a batch file not executable on Windows, so batch files must be saved as ANSI, not Unicode.

    Examples:

    View the current code page:

    chcp

    Change the code page to Unicode/65001:

    chcp 65001

    chown】 Change Owner of File【linux】


    Change file owner

    chown user file

    Change file owner and group

    chown user:group file

    Change owner recursively

    chown -R user directory

    Change ownership to match another file

    chown --reference=/path/to/ref_file file

    weechat】 【linux】


    Set unread marker on all windows

    Ctrl-s Ctrl-u

    Switch buffer left

    Ctrl-p, Alt-left

    Switch buffer right

    Ctrl-n, Alt-right

    Next buffer with activity

    Alt-a

    Switch buffers

    Alt-0...9

    Scroll buffer title

    F9/F10

    Scroll nick list

    F11/F12

    patch】 【linux】


    Patch one file

    patch version1 < version.patch

    Reverse a patch

    patch -R version1 < version.patch

    Patch all files in a directory, adding any missing new files

    -p strips leading slashes

    $ cd dir

    $ patch -p1 -i ../big.patch

    Patch files in a directory, with one level (/) offset

    patch -p1 -r version1/ < version.patch

    rcs】 【linux】


    Initial check-in of file (leaving file active in filesystem)

    ci -u

    Check out with lock

    co -l

    Check in and unlock (leaving file active in filesystem)

    ci -u

    Display version x.y of a file

    co -px.y

    Undo to version x.y (overwrites file active in filesystem with the specified revision)

    co -rx.y

    Diff file active in filesystem and last revision

    rcsdiff

    Diff versions x.y and x.z

    rcsdiff -rx.y -rx.z

    View log of check-ins

    rlog

    Break an RCS lock held by another person on a file

    rcs -u

    pacman】 【linux】


    All the following command work as well with multiple package names

    To search for a package

    pacman -Ss

    To update the local package base and upgrade all out of date packages

    pacman -Suy

    To install a package

    pacman -S

    To uninstall a package

    pacman -R

    To uninstall a package and his depedencies, removing all new orphans

    pacman -Rcs

    To get informations about a package

    pacman -Si

    To install a package from builded package file (.tar.xz)

    pacman -U

    To list the commands provided by an installed package

    pacman -Ql | sed -n -e 's/.*/bin/p' | tail -n +2

    To list explicitly installed packages

    pacman -Qe

    To list orphan packages (installed as dependencies and not required anymore)

    pacman -Qdt

    You can't directly install packages from the Arch User Database (AUR) with pacman.

    You need yaourt to perform that. But considering yaourt itself is in the AUR, here is how to build a package from its tarball.

    Installing a package from AUR is a relatively simple process:

    - Retrieve the archive corresponding to your package from AUR website

    - Extract the archive (preferably in a folder for this purpose)

    - Run makepkg in the extracted directory. (makepkg-s allows you to install any dependencies automatically from deposits.)

    - Install the package created using pacman

    Assuming $pkgname contains the package name.

    wget "https:aur.archlinux.org/packages/${pkgname::2}/$pkgname/$pkgname.tar.gz"

    tar zxvf "$pkgname.tar.gz"

    cd "$pkgname"

    Build the package

    makepkg -s

    Install

    sudo pacman -U

    cd】 change directory【linux】


    Go to the given directory

    cd path/to/directory

    Go to home directory of current user

    cd

    Go up to the parent of the current directory

    cd ..

    Go to the previously chosen directory

    cd -

    distcc】 【linux】


    INSTALL

    ==============================================================================

    Edit /etc/default/distcc and set theses vars

    STARTDISTCC="true"

    ALLOWEDNETS="127.0.0.1 192.168.1.0/24"# Your computer and local computers

    #LISTENER="127.0.0.1"# Comment it

    ZEROCONF="true"# Auto configuration

    REMEMBER 1:

    Start/Restart your distccd servers before using one of these commands.

    service distccd start

    REMEMBER 2:

    Do not forget to install on each machine DISTCC.

    No need to install libs ! Only main host need libs !

    USAGE

    ==============================================================================

    Run make with 4 thread (a cross network) in auto configuration.

    Note: for gcc, Replace CXX by CC and g++ by gcc

    ZEROCONF='+zeroconf' make -j4 CXX='distcc g++'

    Run make with 4 thread (a cross network) in static configuration (2 ip)

    Note: for gcc, Replace CXX by CC and g++ by gcc

    DISTCC_HOSTS='127.0.0.1 192.168.1.69' make -j4 CXX='distcc g++'

    Show hosts aviables

    ZEROCONF='+zeroconf' distcc --show-hosts

    nmcli】 Command line interface to NetworkManager【linux】


    Connect to a wireless access point - Parameters:

    -- the name of your wireless interface

    -- the SSID of the access point

    -- the WiFi password

    nmcli d wifi connect password iface

    Disconnect from WiFi - Parameters:

    -- the name of your wireless interface

    nmcli d wifi disconnect iface

    Get WiFi status (enabled / disabled)

    nmcli radio wifi

    Enable / Disable WiFi

    nmcli radio wifi

    Show all available WiFi access points

    nmcli dev wifi list

    Refresh the available WiFi connection list

    nmcli dev wifi rescan

    Show all available connections

    nmcli con

    Show only active connections

    nmcli con show --active

    Review the available devices

    nmcli dev status

    Add a dynamic ethernet connection - parameters:

    -- the name of the connection

    -- the name of the interface

    nmcli con add type ethernet con-name ifname

    Import OpenVPN connection settings from file:

    nmcli con import type openvpn file

    Bring up the ethernet connection

    nmcli con up

    structs】 structs are like classes, but everything is by default public【cpp】


    Declaration

    ObjectName structName {

         Declaration of variables

        int a;

        string b;

         Constructor

        structName(new_a, new_b) {

            a = new_a;

            b = new_b;

        }

         Implement any public functions below

    };

    Accessing PUBLIC variables

    ObjectName v = structName(5, "Hello"); Creates a struct via the constructor

    std::cout << v.a << " " << v.b << std::endl; Prints to console "5 Hello"

    select】 【postgresql】


    Query all data from a table

    SELECT * FROM table_name;

    Query data from specified columns of all rows in a table

    SELECT column, column2... FROM table;

    Query data and select only unique rows

    SELECT DISTINCT (column) FROM table;

    Query data from a table with a filter

    SELECT * FROM table WHERE condition;

    Set an alias for a column in the result set

    SELECT column_1 AS new_column_1, ...

    FROM table;

    Query data using the LIKE operator

    SELECT * FROM table_name

    WHERE column LIKE '%value%'

    Query data using the BETWEEN operator

    SELECT * FROM table_name

    WHERE column BETWEEN low AND high;

    Query data using the IN operator

    SELECT * FROM table_name

    WHERE column IN (value1, value2,...);

    Constrain the returned rows with LIMIT clause

    SELECT * FROM table_name

    LIMIT limit OFFSET offset

    ORDER BY column_name;

    Query data from multiple using the inner join, left join, full outer join, cross join and natural join:

    SELECT * FROM table1 INNER JOIN table2 ON conditions

    SELECT * FROM table1 LEFT JOIN table2 ON conditions

    SELECT * FROM table1 FULL OUTER JOIN table2 ON conditions

    SELECT * FROM table1 CROSS JOIN table2;

    SELECT * FROM table1 NATURAL JOIN table2;

    Return the number of rows of a table.

    SELECT COUNT (*)

    FROM table_name;

    Sort rows in ascending or descending order

    SELECT column, column2, ...

    FROM table

    ORDER BY column ASC [DESC], column2 ASC [DESC],...;

    Group rows using GROUP BY clause.

    SELECT *

    FROM table

    GROUP BY column_1, column_2, ...;

    Filter groups using the HAVING clause.

    SELECT *

    FROM table

    GROUP BY column_1

    HAVING condition;

    Combine the result set of two or more queries with UNION operator:

    SELECT * FROM table1

    UNION

    SELECT * FROM table2;

    Minus a result set using EXCEPT operator:

    SELECT * FROM table1

    EXCEPT

    SELECT * FROM table2;

    Get intersection of the result sets of two queries:

    SELECT * FROM table1

    INTERSECT

    SELECT * FROM table2;

    dracut】 【linux】


    add driver to initrd/initramfs (nvme in this case)

    dracut --add-drivers nvme -f /boot/initrd-$(uname -r).img $(uname -r)

    ObjectOrientation】 【scala】


    constructor params - private

    class C(x: R) same as

    class C(private val x: R)

    var c = new C(4)

    constructor params - public

    class C(val x: R)

    var c = new C(4)

    c.x

    class C(var x: R) {

       constructor is class body

      assert(x > 0, "positive please")

      

       declare a public member

      var y = x

      

       declare a gettable but not settable member

      val readonly = 5

      

       declare a private member

      private var secret = 1

      

       alternative constructor

      def this = this(42)

    }

    anonymous class

    new{ ... }

    define an abstract class. (non-createable)

    abstract class D { ... }

    define an inherited class.

    class C extends D { ... }

    class D(var x: R)

    inheritance and constructor params. (wishlist: automatically pass-up params by default)

    class C(x: R) extends D(x)

    define a singleton. (module-like)

    object O extends D { ... }

    traits.

    trait T { ... }

    interfaces-with-implementation. no constructor params

    mixin-able: http:docs.scala-lang.org/tutorials/tour/mixin-class-composition.html

    class C extends T { ... }

    class C extends D with T { ... }

    multiple traits.

    trait T1; trait T2

    class C extends T1 with T2

    class C extends D with T1 with T2

    must declare method overrides.

    class C extends D { override def f = ...}

    create object.

    new java.io.File("f")

    new List[Int] BAD type error: abstract type

    List(1,2,3) GOOD instead, convention: callable factory shadowing the type

    class literal.

    classOf[String]

    type check (runtime)

    x.isInstanceOf[String]

    type cast (runtime)

    x.asInstanceOf[String]

    ascription (compile time)

    x: String

    pbcopy】 Place standard output in the clipboard.【linux】


    Place the contents of a file in the clipboard:

    pbcopy < file

    Place the results of a command in the clipboard:

    find . -type t -name "*.png" | pbcopy

    ncat】 Concatenate and redirect sockets【linux】


    Connect mode (ncat is client) | default port is 31337

    ncat []

    Listen mode (ncat is server) | default port is 31337

    ncat -l [] []

    Transfer file (closes after one transfer)

    ncat -l [] [] < file

    Transfer file (stays open for multiple transfers)

    ncat -l --keep-open [] [] < file

    Receive file

    ncat [] [] > file

    Brokering | allows for multiple clients to connect

    ncat -l --broker [] []

    Listen with SSL | many options, use ncat --help for full list

    ncat -l --ssl [] []

    Access control

    ncat -l --allow

    ncat -l --deny

    Proxying

    ncat --proxy [:] --proxy-type {http | socks4} []

    Chat server | can use brokering for multi-user chat

    ncat -l --chat [] []

    iwconfig】 【linux】


    Display wireless settings of the first wireless adapter

    iwconfig wlan0

    Take down / up the wireless adapter

    iwconfig wlan0 txpower {on|auto|off}

    Change the mode of the wireless adapter

    iwconfig wlan0 mode {managed|ad-hoc|monitor}

    cmdkey】 Create, list or delete stored user names, passwords or credentials.【win】


    Syntax

          cmdkey [{/add:TargetName|/generic:TargetName}]

             {/smartcard|/user:UserName [/pass:Password]}

                [/delete{:TargetName|/ras}]

                   /list:TargetName

    Key:

       /add Add a user name and password to the list.

       TargetName The computer or domain name that this entry will be associated with.

       /generic Add generic credentials to the list (used by RDC).

       /smartcard Retrieve the credential from a smart card.

       /user:UserName The user or account name to store with this entry.

                       If UserName is not supplied, it will be requested.

       /pass:Password The password to store with this entry. If Password is not supplied, it will be requested.

       /delete: Delete a user name and password from the list.

                       If TargetName is specified, that entry will be deleted.

                       If /ras is specified, the stored remote access entry will be deleted.

       /list Display the list of stored user names and credentials.

                       If TargetName is not specified, all stored user names and credentials will be listed.

    The credentials created by CMDKEY can also be created and edited in the GUI Control Panel | Credential Manager

    Credentials setup as type /generic:TERMSRV will be used by Remote Desktop Connection, so you will be able to connect as the given user without being prompted for a password. If the password is changed you will need to update the stored credential.

    By default the credentials are stored in C:\users\username\AppData\Roaming\Microsoft\Credentials\

    (around 400 bytes per credential)

    If more than one smart card is found, cmdkey will prompt the user to specify which one to use.

    Once stored, passwords are not displayed by cmdkey.

    Examples

    Display a list of stored user names and credentials:

    cmdkey /list

    Add a generic TERMSRV credential for user PeteZ (on domain dom64) to access the computer Server64:

    cmdkey /generic:TERMSRV/Server64 /user:dom64\PeteZ /pass:p4g67hjyy23

    Delete the stored TERMSRV credential for Server64:

    cmdkey /delete TERMSRV/Server64

    Add a user name and password for user Kate to access computer Server64 with the password z5rd63hGtjH7:

    cmdkey /add:server64 /user:Kate /pass:z5rd63hGtjH7

    Add a user name for user Kate to access computer Server64 and prompt for a password whenever Server64 is accessed:

    cmdkey /add:server64 /user:Kate

    Delete the stored credential for Server64:

    cmdkey /delete:Server64

    xcodebuild】 【linux】


    xcodebuild

    Build Xcode projects.

    Build workspace:

    xcodebuild -workspace workspace_name.workspace -scheme scheme_name -configuration configuration_name clean build SYMROOT=SYMROOT_path

    Build project:

    xcodebuild -target target_name -configuration configuration_name clean build SYMROOT=SYMROOT_path

    Show SDKs:

    xcodebuild -showsdks

    csplit】 【linux】


    Split a file based on pattern

    csplit input.file '/PATTERN/'

    Use prefix/suffix to improve resulting file names

    csplit -f 'prefix-' -b '%d.extension' input.file '/PATTERN/' '{*}'

    truncate】 【linux】


    To clear the contents from a file:

    truncate -s 0 file.txt

    To truncate a file to 100 bytes:

    truncate -s 100 file.txt

    To truncate a file to 100 KB:

    truncate -s 100K file.txt

    (M, G, T, P, E, Z, and Y may be used in place of "K" as required.)

    eject】 eject removable media【linux】


    Eject any available device

    CD-ROM, floppy disk, tape, or JAZ or ZIP disk

    eject

    Eject a device by its name

    eject /dev/cdrom

    Close the tray using eject command

    eject -t

    Lock the hardware eject button

    eject -i on

    Unlock the hardware eject button

    eject -i off

    svcadm】 Manipulate service instances (Solaris)【linux】


    Enable a service in the service database:

    svcadm enable service_name

    Disable service:

    svcadm disable service_name

    Restart a running service:

    svcadm restart service_name

    Command service to re-read configuration files:

    svcadm refresh service_name

    Clear a service from maintenance state and command it to start:

    svcadm clear service_name

    luarocks】 LuaRocks is the package manager for Lua modules【lua】


    LuaRocks is the package manager for Lua modules

    install luarocks

    wget https:luarocks.org/releases/luarocks-2.4.1.tar.gz

    tar zxpf luarocks-2.4.1.tar.gz

    cd luarocks-2.4.1

    ./configure; sudo make bootstrap

    install lua package

    luarocks install luasocket

    search for lua package

    luarocks search luasec

    strace】 【linux】


    Basic stracing

    strace

    save the trace to a file

    strace -o strace.out

    follow only the open() system call

    strace -e trace=open

    follow all the system calls which open a file

    strace -e trace=file

    follow all the system calls associated with process

    management

    strace -e trace=process

    follow child processes as they are created

    strace -f

    count time, calls and errors for each system call

    strace -c

    trace a running process (multiple PIDs can be specified)

    strace -p

    cups】 Manage printers through CUPS【linux】


    Manage printers through CUPS:

    http:localhost:631 (in web browser)

    Print file from command line

    lp myfile.txt

    Display print queue

    lpq

    Remove print job from queue

    lprm 545

    or

    lprm -

    Print log location

    /var/log/cups

    Reject new jobs

    cupsreject printername

    Accept new jobs

    cupsaccept printername

    siteciphers】 Checks the available ciphers for the SSL of an https site【linux】


    Determine the available SSL ciphers for an https website

    siteciphers github.com

    Determine the ciphers setting the delay between requests (default is 1 sec)

    siteciphers -d 0.75 travis-ci.org

    cursor】 【mongo】


    Show number of documents in the collection

    db.books.find().count()

    Limit the number of documents to return

    db.books.find().limit(2)

    Return the result set after skipping the first n number of documents

    db.books.find().skip(2)

    Sort the documents in a result set in ascending or descending order of field values

    db.books.find().sort( {title : 1} )

    value = 1 for ascending, -1 for descending

    Display formatted (more readable) result

    db.books.find({}).pretty()

    carthage】 A dependency management tool for Cocoa applications (Mac OS X)【linux】


    Download the latest version of all dependencies mentioned in Cartfile, and build them:

    carthage update

    Update dependencies, but only build for iOS:

    carthage update --platform ios

    Update dependencies, but don't build any of them:

    carthage update --no-build

    Download and rebuild the current version of dependencies (without updating them):

    carthage bootstrap

    Rebuild a specific dependency:

    carthage build dependency

    ncdu】 【linux】


    Save results to file

    ncdu -o ncdu.file

    Read from file

    ncdu -f ncdu.file

    Save results to compressed file

    ncdu -o-| gzip > ncdu.file.gz

    Read from compressed file

    zcat ncdu.file.gz | ncdu -f-

    xsltproc】 【linux】


    xsltproc

    Transform XML with XSLT to produce output (usually HTML or XML).

    Transform an XML file with a specific XSLT stylesheet:

    xsltproc --output output.html stylesheet.xslt xmlfile.xml

    Pass a value to a parameter in the stylesheet:

    xsltproc --output output.html --stringparam name value stylesheet.xslt xmlfile.xml

    Manipulatingcollections】 【scala】


    map

    works by applying a function to each element in the list

    val l = List(1,2,3,4,5)

    l map (num => num * 2) returns List(2,4,6,8,10)

    wildcard sugar with map

    this subsititutes "_" for the current value when iterating over the collection

    l map (_ * 2) returns List(2,4,6,8,10)

    map with partial functions

    allows the ability to provide different map functions for different discrete cases

    this example will increment odd numbers by one, but double even numbers

    l map { note: the curly brackets allow us to make the map multi-line and use 'case' statements (see PatternMatching)

        case num if num % 2 == 0 => num * 2

        case other => other + 1

    } returns List(2,4,4,8,6)

    filter

    removes elements from a collection where the filter function returns false

    l filter (_ % 2 == 0) returns List(2,4)

    filterNot

    l filter (_ % 2 == 0) returns List(1,3,5)

    collect

    this is like a combination of filter and map

    this example shows that collect essentially filters by "i < 3" then maps with "_ + 20"

    l collect { note: collect requires a partial function, so we have to use curly brackets and 'case' statements

        case i if i < 3 => i + 20

    } returns List(21, 22)

    find

    this will return the first element (going left to right) that returns true

    it returns an option to handle the case where no element is found

    l find (_ % 2 == 0) returns Some(2)

    l find (_ == 55) returns None

    exists

    similar to find but returns a boolean instead if an element exists rather than an option

    l exists (_ % 2 == 0) returns true

    l exists (_ % 2 != 0) returns true

    l exists (_ == 10) returns false

    forall

    very similar to exists. Will check a condition applies to all elements on a collection and return a boolean

    List(1,2,3) forall (_ < 5) returns true

    List(1,2,6) forall (_ < 5) returns false

    reduce

    collapses a collection into a single element using a given function (this will fail with an empty list)

    operates on two elements at a time, "reducing" them into one, so only one element is returned

    l reduce ( (a, b) => a + b ) same as

    l reduce (_ + _) returns 15, the result of adding 1, 2, 3, 4 and 5

    fold

    this is the same as reduce except a "default" is provided, in case of an empty list.

    List(1,2,3,4,5).fold(50)(_ + _) returns 15

    List() .fold(50)(_ + _) returns 50, the default

    flatten

    must be used on something in the shape F[F[A]] eg. List[List[Int]]

    squashes two-dimensional collections into one-dimensional collections

    List(List(1,2,3), List(4,5)).flatten returns List(1,2,3,4,5)

    flatMap

    maps then flattens in one function

    in this example, we will map and flatMap a List[Int] using a function that turns each Int into a List[Int]

    List(1,2,3) map {

        num => List(num, num)

    }

    for this example, mapping returns List(List(1,1),List(2,2),List(3,3))

    vs

    List(1,2,3) flatMap {

        num => List(num, num)

    } returns List(1,1,2,2,3,3)

    isEmpty

    returns true if the collections is empty

    List(1,2,3).isEmpty returns false

    List().isEmpty returns true, same as

    Nil.isEmpty

    note: All lists terminate with "Nil" meaning that List() == List.empty == Nil

    diff

    returns the "difference" of two collections, these are the elements that exist in the first but not the second

    val oneToSix = List(1, 2, 3, 4, 5, 6)

    val fourToNine = List(4, 5, 6, 7, 8, 9)

    oneToSix diff (fourToNine) returns List(1,2,3)

    fourToNine diff (oneToSix) returns List(7,8,9)

    intersect

    returns the "intersection" of two collections, these are the elements that exist in both collections

    val oneToSix = List(1, 2, 3, 4, 5, 6)

    val fourToNine = List(4, 5, 6, 7, 8, 9)

    oneToSix intersect (fourToNine) returns List(4,5,6)

    fourToNine intersect (oneToSix) returns List(4,5,6)

    union

    returns the concatenation of the two lists

    val oneToSix = List(1, 2, 3, 4, 5, 6)

    val fourToNine = List(4, 5, 6, 7, 8, 9)

    oneToSix union fourToNine same as

    oneToSix ++ fourToNine returns List(1, 2, 3, 4, 5, 6, 4, 5, 6, 7, 8, 9)

    distinct

    removes duplicates from a collection

    List(1,1,2,3,3,4,5).distinct returns List(1,2,3,4,5)

    drop

    this will remove a given amount of elements from the front of a collection

    List(1,2,3,4,5).drop(1) returns List(2,3,4,5)

    List(1,2,3,4,5).drop(3) returns List(4,5)

    dropWhile

    this will continue to remove elements until the condition returns false

    List(1,2,3,4,5).dropWhile(_ < 4) returns List(4,5), removing all elements smaller than four

    List(1,2,3,4,5).dropWhile(_ % 2 == 0) returns List(1,2,3,4,5), it removes nothing as the first element returned false

    take

    the opposite of drop, returns the given number of elements from the front of a collection

    List(1,2,3,4,5).take(1) returns List(1)

    List(1,2,3,4,5).take(3) returns List(1,2,3)

    takeWhile

    this will continue to take elements until the condition returns false

    List(1,2,3,4,5).takeWhile(_ < 4) returns List(1,2,3), taking all elements smaller than four

    List(1,2,3,4,5).takeWhile(_ % 2 == 0) returns List(), it takes nothing as the first element returned false

    fill

    this will create a List of a given length, filled with given elements

    List.fill(3)(5) returns List(5,5,5)

    List.fill(5)(3) returns List(3,3,3,3,3)

    List.fill(3)("a") returns List("a", "a", "a")

    size

    returns the length of a collection

    List(1,2,3,2).size returns 4

    min

    returns the minimum value

    List(1,2,3).min returns 1

    max

    returns the maximum value

    List(1,2,3).min returns 3

    partition

    returns two collections as a Tuple2 eg. (List[Int], List[Int]), see DataStructures for more on Tuple

    one collection containing all the "false" and another containing all the "true" elements

    List(1,2,3,4).partition(_ % 2 == 0) returns (List(2,4), List(1,3))

    List(1,2,3,4).partition(_ < 4) returns (List(1,2,3), List(4))

    span

    similar to partition, will split the list at the point that a condition returns false

    List(1,3,5,4,2).span(_ < 3) returns (List(1), List(3,5,4,2))

    List(1,3,5,4,2).span(_ != 5) returns (List(1, 3), List(5,4,2))

    groupBy

    returns two collections as a Map

    List(1,2,3,4).groupBy(_ % 2 == 0) returns Map(false -> List(1,3), true -> List(2,4))

    List(1,2,3,4).groupBy(identity) returns Map(1 -> List(1), 2 -> List(2), 3 -> List(3), 4 -> List(4))

    splitAt

    splits a collection before the given index

    List(1,7,4,6,5).splitAt(2) returns (List(1,7), List(4,6,5))

    slice

    returns a subset a collection between two indexes

    List("a","b","c","d","e").slice(2,4) returns List("c","d")

    zip

    joins two collections as a List of Tuple2, joining index 0 from one list to index 0 of the second list, 1 to 1, 2 to 2 etc.

    List(1,2,3) zip List("x", "y", "z") returns List((1,"a"), (2,"b"), (3,"c"))

    List(1,2,3,4,5) zip List("x", "y", "z") returns List((1,"a"), (2,"b"), (3,"c")) as there are only 3 elements to zip with

    zipWithIndex

    adds index numbers to a collection, returning a List of Tuple2

    List("a", "b", "c").zipWithIndex returns List(("a",0), ("b",1), ("c", 2))

    unzip

    opposite of zip, converts a List of Tuple2 into a Tuple2 of Lists

    List(("a",0), ("b",1), ("c", 2)).unzip returns (List("a", "b", "c"), List(0, 1, 2))

    reverse

    List(1,2,3).reverse returns List(3,2,1)

    head

    returns the first element of a collection

    List(1,2,3).head returns 1

    headOption

    returns the first element of a collection as an Option, returns None in the case of an empty collection

    List(1,2,3).headOption returns Some(1)

    List().headOption returns None

    tail

    returns everything after the Head of a collection

    List(1,2,3).tail returns List(2,3), same as

    List(1,2,3).drop(1)

    last

    List(1,2,3).last returns 3

    cut】 It can be used to cut parts of a line by delimiter, byte position, and character【linux】


    To cut out the third field of text or stdoutput that is delimited by a #:

    cut -d# -f3

    nc】 【linux】


    To open a TCP connection to port 42 of host.example.com, using port 31337 as the source port, with a timeout of 5 seconds:

    nc -p 31337 -w 5 host.example.com 42

    To open a UDP connection to port 53 of host.example.com:

    nc -u host.example.com 53

    To open a TCP connection to port 42 of host.example.com using 10.1.2.3 as the IP for the local end of the connection:

    nc -s 10.1.2.3 host.example.com 42

    To create and listen on a UNIX-domain stream socket:

    nc -lU /var/tmp/dsocket

    To connect to port 42 of host.example.com via an HTTP proxy at 10.2.3.4, port 8080. This example could also be used by ssh(1); see the ProxyCommand directive in ssh_config(5) for more information.

    nc -x10.2.3.4:8080 -Xconnect host.example.com 42

    The same example again, this time enabling proxy authentication with username "ruser" if the proxy requires it:

    nc -x10.2.3.4:8080 -Xconnect -Pruser host.example.com 42

    To choose the source IP for the testing using the -s option

    nc -zv -s source_IP target_IP Port

    convert】 Convert a FAT16 or a FAT32 DISK volume to NTFS.【win】


    Syntax

          convert [Volume] /fs:ntfs [/v] [/cvtarea:FileName] [/nosecurity] [/x]

    Key

       Volume The drive letter (followed by a colon), mount point,

                or volume name to convert to NTFS.

       /fs:ntfs Convert the volume to NTFS. Required.

       /v Run convert in verbose mode, which displays all messages

                during the conversion process.

       /cvtarea:FileName

                Specifies that the Master File Table (MFT) and other NTFS metadata

                files are written to an existing, contiguous placeholder file.

                This file must be in the root directory of the file system to be converted.

                Use of the /cvtarea parameter can result in a less fragmented file system

                after conversion.

                For best results, the size of this file should be 1 KB multiplied by the number of files

                and directories in the file system, although the convert utility accepts files of any size.

                Important You must create the placeholder file by using the fsutil file createnew command

                prior to running convert. Convert does not create this file for you.

                Convert overwrites this file with NTFS metadata.

                After conversion, any unused space in this file is freed.

       /nosecurity

                The security settings on the converted files and directories allow access by all users.

       /x Dismount the volume, if necessary, before it is converted.

                Any open handles to the volume will no longer be valid.

       /? Display help at the command prompt.

    If convert cannot lock the drive (for example, the drive is the system volume or the current drive), you are given the option to convert the drive the next time you restart the computer. If you cannot restart the computer immediately to complete the conversion, plan a time to restart the computer and allow extra time for the conversion process to complete.

    For volumes converted from FAT or FAT32 to NTFS:

    Due to existing disk usage, the MFT is created in a different location than on a volume originally formatted with NTFS, so volume performance might not be as good as on volumes originally formatted with NTFS. For optimal performance, consider recreating these volumes and formatting them with the NTFS file system. Volume conversion from FAT or FAT32 to NTFS leaves the files intact, but the volume might lack some performance benefits compared to volumes initially formatted with NTFS. For example, the MFT might become fragmented on converted volumes. In addition, on converted boot volumes, convert applies the same default security that is applied during Windows Setup.

    Example

    Convert the volume on drive E: to NTFS and display all messages during the conversion process:

    C:\> convert e: /fs:ntfs /v

    scrot】 GUI screenshot tool for taking, editing screenshots【linux】


    Take screenshot of the current window

    scrot -u

    Take screenshot of the current window including border

    scrot -ub

    Interactively select a window or rectangle with the mouse

    scrot -s

    Capture the screenshot after 5 seconds, display countdown time

    scrot -u -d 5 -c

    chkdsk】 Check Disk - check and repair disk problems【win】


    Syntax

          CHKDSK [drive:][[path]filename] [/F] [/V] [/R] [/L[:size]]

    Key

       [drive:] The drive to check. Drive letter followed by a colon, mount point or volume name.

       filename File(s) to check for fragmentation (FAT only).

       /F Automatically Fix file system errors on the disk.

       /X Fix file system errors on the disk, Implies /F

                  dismounts the volume first, closing all open file handles.

       /R Scan for and attempt Recovery of bad sectors.

       /B NTFS only: Re-evaluate bad clusters on the volume. Implies /R Windows10+

       /V Display the full path and name of every file on the disk.

       /L:size NTFS only: change the log file size to the specified number of kilobytes.

                  If size is not specified, displays the current log size and the drive type

                  (FAT or NTFS).

       /C NTFS only: Skip directory corruption checks.

       /I NTFS only: Skip corruption checks that compare directory entries to the

                  file record segment (FRS) in the volume's master file table (MFT)

       /scan NTFS only: Run an online scan on the volume.

       /forceOfflineFix

                  NTFS only: Must be used with /scan

                  Bypass all online repair; all defects found are queued for offline repair

                  i.e. chkdsk /spotfix

       /perf NTFS only: Must be used with /scan

                  Uses more system resources to complete a scan as fast as possible. This may

                  have a negative impact on other running tasks.

       /spotfix NTFS only: Run spot fixing on the volume.

       /sdCleanup NTFS only: Garbage collect unneeded security descriptor data, implies /F

       /offlineScanandFix

                  Run an offline scan and fix on the volume.

       /freeOrphanedChains

                  FAT/FAT32/exFAT only: Free any orphaned cluster chains instead of recovering

                  their contents.

       /markClean FAT/FAT32/exFAT only: Mark the volume clean if no corruption was detected even

                  if /F was not specified.

    Examples

    CHKDSK C: /F

    Fixing Errors /F

    If the drive is the boot partition, you will be prompted to run the check during the next boot

    If you specify the /f switch, chkdsk will show an error if open files are found on the disk.

    Chkdsk /f will lock the volume, making data unavailable until chkdsk is finished.

    If you use chkdsk /f on a disk with a very large number of files (millions), chkdsk can take a long time to complete.

    When you delete a file or folder that has 'custom' permissions, the ACL is not deleted, it is cached. Chkdsk /f will remove ACLs that are no longer used. This is often the cause of the rather worrying message: "Windows found problems with the file system. Run chkdsk with the /F (fix) option to correct these."

    It is normal for chkdsk /F to remove unused index entries and unused security descriptors every time you run it, these do not indicate a problem with the file system.

    Scan only (without /f switch)

    If a file needs to be fixed chkdsk will alert you with a message but will not fix the error(s).

    chkdsk can report lost allocation units on the disk - it will produce this report even if the files are in-use (open). If corruption is found, consider closing all files and repairing the disk with /F.

    Running chkdsk on a data volume that is in use by another program or process can incorrectly report errors when none are present. To avoid this, close all programs or processes that have open handles to the volume.

    On computers running Windows 2003 SP1 and later, chkdsk automatically creates a shadow copy, so you can check volumes that are 'in use' by another program or process. This enables an accurate report against a live file server. On earlier versions of Windows, chkdsk would always lock the volume, making data unavailable.

    Run at Bootup

    Running at bootup is often the easiest way to close all open file handles.

    Use chkdsk, chkntfs or the FSUTIL dirty commands to set or query the volumes 'dirty' bit so that Windows will run chkdsk when the computer is restarted. This setting is also found in the BootExecute value under HKLM\System\CurrentControlSet\Control\Session Manager

    Event Logs

    Chkdsk will log error messages in the Event Viewer - System Log.

    Chkdsk /f removes ACLs that are no longer used and reports this in the Event Viewer - Application Log.

    Cluster (or block) Size

    CHKDSK produces a report that shows the the block /cluster size

    typically: "4096 bytes in each allocation unit."

    When the cluster size is greater than 4 KB on an NTFS volume, none of the NTFS compression functions are available.

    Exit codes

    0 No errors were found

    1 Errors were found and fixed.

    2 Could not check the disk, did not or could not fix errors.

    Notes:

    Consider the time required to run Chkdsk to repair any errors that occur. Chkdsk times are determined by the number of files on the volume and by the number of files in the largest folder. Chkdsk performance was improved by 30% under Windows 2003 and around 50% in 2008 R2.

    To issue chkdsk on a hard drive you must be a member of the Administrators group.

    When CHKDSK is set to run at boot-up there is a delay to allow the check to be cancelled - this can be configured in the registry:

    HKLM\System\CurrentControlSet\Control\Session Manager

    REG_DWORD:AutoChkTimeOutData

    The value is the time in seconds that you want CHKDSK to wait (0 = no delay) default is 10 seconds.

    Chkdsk is also available from the Recovery Console (with different parameters.)

    currency】 【linux】


    Currency (Bash-Snippets)

    A realtime currency converter

    To convert between currencies (guided)

    currency

    To convert between currencies (by supplying arguments)

    First argument is base currency second is the currency being exchanged to

    currency USD EUR 14.38

    color】 Sets the default console foreground and background colours.【win】


    Syntax

          COLOR [background][foreground]

    Colour attributes are specified by 2 of the following hex digits. There should be no space between the two color numbers.

    Each digit can be any of the following values:

        0 = Black

        8 = Gray

        1 = Blue

        9 = Light Blue

        2 = Green

        A = Light Green

        3 = Aqua

        B = Light Aqua

        4 = Red

        C = Light Red

        5 = Purple

        D = Light Purple

        6 = Yellow

        E = Light Yellow

        7 = White

        F = Bright White

    If no argument is given, COLOR restores the colour to what it was when CMD.EXE started.

    Colour values are assigned in the following order:

    The DefaultColor registry value.

    The CMD /T command line switch

    The current colour settings when cmd was launched

    The COLOR command sets ERRORLEVEL to 1 if an attempt is made to execute the COLOR command with a foreground and background colour that are the same.

    The default terminal color is COLOR 07, white on black

    The COLOR command will change the color of all the text in the window. To change the color of individual words/characters/paragraphs ANSI color escapes can be used. These are available in Windows versions greater than 1511.

    New default Color schemes

        In Windows 10 clean-install versions greater than build 16257 the default colour scheme has been changed to modernize the look of the Windows Console suitable for modern high-contrast LCD displays.

        Samples of the new colors can be found on the ANSI color page, you can also display them with ColorTool.exe -c

        If using ColorTool, you may want to tinker with the new values: "So up until very recently the console only supported 16 colours at a time. When the PowerShell team decided they wanted a very specific dark blue as the background colour, rather than altering the colour value for dark or light blue, they instead changed dark magenta to blue and used that as the background colour".

    24 bit colors

        The new W10 Console also adds full 24-bit color support, this is primarily for Linux compatibility so the console properties page and the default Windows color mappings still use just 16 colors, there is no plan to add additional console colors to the Win32 API.

        To take advantage of the new colors use ColorTool.exe and install a theme, or use the VT100 sequences described here.

        When the VT100 sequences are used with a version of the Windows Console that supports 24-bit colors they will display the desired RGB color, older consoles will choose the nearest appropriate color from the existing 16 color table.

    Errorlevels

        If the color was successfully changed %ERRORLEVEL% = 0

        Background and foreground colors are the same (will fail) = 1

        e.g. COLOR 00

    COLOR is an internal command.

    If Command Extensions are disabled, the COLOR command will not function.

    schema】 【postgresql】


    List schemas

    SELECT schema_name FROM information_schema.schemata;

    SELECT nspname FROM pg_catalog.pg_namespace;

    Create schema

    CREATE SCHEMA IF NOT EXISTS ;

    Drop schema

    DROP SCHEMA IF EXISTS CASCADE;

    channels】 【golang】


    ch := make(chan int) create a channel of type int

    ch <- 42 Send a value to the channel ch.

    v := <-ch Receive a value from ch

    Create a buffered channel.

    Writing to a buffered channels does not block

    if less than unread values have been written.

    ch := make(chan int, 100)

    Non-buffered channels block.

    Read blocks when no value is available,

    write blocks if a value already has been written but not read.

    close(ch) closes the channel (only sender should close)

    read from channel and test if it has been closed

    v, ok := <-ch

    if ok is false, channel has been closed

    Read from channel until it is closed

    for i := range ch {

        fmt.Println(i)

    }

    select blocks on multiple channel operations,

    if one unblocks, the corresponding case is executed

    func doStuff(channelOut, channelIn chan int) {

        select {

        case channelOut <- 42:

            fmt.Println("We could write to channelOut!")

        case x := <- channelIn:

            fmt.Println("We could read from channelIn")

        case <-time.After(time.Second * 1):

            fmt.Println("timeout")

        }

    }

    COMPACT】 Display or alter the compression of files on NTFS partitions.【win】


    Syntax

          COMPACT [/C | /U] [/S[:dir]] [/A] [ /I] [/F] [/Q] [/EXE[:algorithm]]

             [/CompactOs[:option] [/WinDir:dir] [filename [...]]

    Key

       /C Compress the specified files.

                 Directories will be marked so that files added afterward will be compressed.

       /U Uncompress the specified files.

                 Directories will be marked so that files added afterward will not be compressed.

       /S Perform the specified operation on files in the given directory and all subdirectories.

                 The default "dir" is the current directory.

       /A Display files with the hidden or system attributes. These files are omitted by default.

       /I Continue performing the specified operation even after errors have occurred.

                 By default, COMPACT will stop when an error is encountered.

       /F Force the compress operation on all specified files, even those which are already

                 compressed. Already-compressed files are skipped by default.

       /Q Report only the most essential information.

       /EXE Use compression optimised for executable files which are read frequently and not modified,

                 Supported algorithms are:

                   XPRESS4K (fastest) default

                   XPRESS8K

                   XPRESS16K

                   LZX (most compact)

       /CompactOs Set or query the systems compression state.

                 Supported options are:

                   query - Query the systems compact state.

                   always - Compress all OS binaries and set the system state to non-compact.

                   never - Uncompress all OS binaries and set the system state to compact which remains

                            unless an administrator changes it.

       /WinDir Used with /CompactOs:query, when querying the offline OS. Specifies the directory where

                 Windows is installed.

       filename Specifies a pattern, file, or directory.

    Used without parameters, COMPACT displays the compression state of the current directory and any files it contains.

    You can use multiple filenames and wildcards. You must put spaces between multiple parameters.

    xscreensaver】 【linux】


    lock screen sver

    xscreensaver-command -lock

    function】 【scala】


    define function

    GOOD

    def f(x: Int) = { x*x }

    BAD

    hidden error: without = it’s a Unit-returning procedure; causes havoc

    def f(x: Int) { x*x }

    define function

    GOOD

    def f(x: Any) = println(x)

    BAD

    syntax error: need types for every arg.

    def f(x) = println(x)

    type alias

    type R = Double

    call-by-value

    def f(x: R)

    call-by-name (lazy parameters)

    def f(x: => R)

    anonymous function

    (x:R) => x*x

    anonymous function: underscore is positionally matched arg.

    (1 to 5).map(_*2) vs.

    (1 to 5).reduceLeft( _+_ )

    anonymous function: to use an arg twice, have to name it.

    (1 to 5).map( x => x*x )

    anonymous function: bound infix method. Use 2*_ for sanity’s sake instead.

    GOOD

    (1 to 5).map(2*)

    BAD

    (1 to 5).map(*2)

    anonymous function: block style returns last expression.

    (1 to 5).map { x => val y=x*2; println(y); y }

    anonymous functions: pipeline style. (or parens too).

    (1 to 5) filter {_%2 == 0} map {_*2}

    anonymous functions: to pass in multiple blocks, need outer parens.

    def compose(g:R=>R, h:R=>R) = (x:R) => g(h(x))

    val f = compose({_*2}, {_-1})

    currying, obvious syntax.

    val zscore = (mean:R, sd:R) => (x:R) => (x-mean)/sd

    currying, obvious syntax

    def zscore(mean:R, sd:R) = (x:R) => (x-mean)/sd

    currying, sugar syntax. but then:

    def zscore(mean:R, sd:R)(x:R) = (x-mean)/sd

    need trailing underscore to get the partial, only for the sugar version.

    val normer = zscore(7, 0.4) _

    using curried parameters with a partially applied function

    can be called as "add(1)(2)" to return "3"

    def add(x: Int) = x + (_: Int)

    generic type.

    def mapmakeT(seq: List[T]) = seq.map(g)

    infix sugar.

    5.+(3); 5 + 3

    (1 to 5) map (_*2)

    varargs

    def sum(args: Int*) = args.reduceLeft(_+_)

    default parameters

    def countTo(i: Int = 5) = 1 to i

    countTo(3) = Range(1,2,3)

    countTo() = Range(1,2,3,4,5)

    higher order functions

    as long as a function returns the correct type, it can be used as a parameter in another function

    def sum(a: Int, b: Int): Int = a + b

    def double(x: Int): Int = x * 2

    double(sum(1, 1)) returns 4

    udisksctl】 【linux】


    Get info about block device

    udisksctl info -b

    Mounting device

    udisksctl mount --block-device

    Unmounting device

    udisksctl unmount --block-device

    Get help

    udisksctl help

    rpm2cpio】 【linux】


    List contents of RPM

    rpm2cpio foo.rpm | cpio -vt

    Extract contents of RPM

    rpm2cpio foo.rpm | cpio -vid

    cd】 Change Directory - Select a Folder (and drive)【win】


    Syntax

          CD [/D] [drive:][path]

          CD [..]

    Key

       /D : change the current DRIVE in addition to changing folder.

    CHDIR is a synonym for CD.

    Tab Completion

        Tab completion allows changing the current folder by entering just part of the path and pressing TAB.

           C:> CD Prog [PRESS TAB]

           Will go to C:\Program Files\

        Tab Completion is disabled by default, it has been known to create difficulty when using a batch script to process text files that contain TAB characters.

        Tab Completion is turned on by setting the registry value shown below:

        REGEDIT4

        [HKEY_CURRENT_USER\Software\Microsoft\Command Processor]

        "CompletionChar"=dword:00000009

    A Current Directory for each drive?

        Originally in MS-DOS, each drive had its own current directory, for complex historical reasons.

        Now in Win32, there is one global current directory, but at the command line the appearance is still maintained that each drive has its own current directory, this is a fake-out by cmd.exe.

        The location for each drive is stored using the undocumented environment variables =A:, =B:, =C: etc.

        The only reason you need to be aware of this is that GUI Windows applications may have a different current directory than the command prompt. Similarly two CMD sessions can each have a different current directory.

    Errorlevels

        If the Current directory was changed: %ERRORLEVEL% = 0

        If the Directory does not exist or is not accessible or if a bad switch given: %ERRORLEVEL% = 1

    CHDIR is a synonym for CD

    CD is an internal command.

    Examples

    Change to the parent directory:

    C:\Work> CD ..

    Change to the grant-parent directory:

    C:\Work\backup\January> CD ..\..

    Change to the ROOT directory:

    C:\Work\backup\January> CD \

    Display the current directory in the specified drive:

    C:\> CD D:

    Display the current drive and directory:

    C:\Work> CD

    Display the current drive and directory:

    C:\Work> ECHO "%CD%"

    In a batch file to display the location of the batch script file (%0)

    C:\> ECHO "%~dp0"

    In a batch file to CD to the location of the batch script file (%0)

    C:\> CD /d "%~dp0"

    Move down the folder tree with a full path reference to the ROOT folder...

    C:\windows> CD \windows\java

    C:\windows\java>

    Move down the folder tree with a reference RELATIVE to the current folder...

    C:\windows> CD java

    C:\windows\java>

    Move up and down the folder tree in one command...

    C:\windows\java> CD ..\system32

    C:\windows\system32>

    If Command Extensions are enabled, which they are by default, the CD command is enhanced as follows:

        The current directory string is not CASE sensitive.

        So CD C:\wiNdoWs will set the current directory to C:\Windows

        CD does not treat spaces as delimiters, so it is possible to CD into a subfolder name that contains a space without surrounding the name with quotes.

        For example:

        cd \My folder

        is the same as:

        cd "\My folder"

        An asterisk can be used to complete a folder name

        e.g. C:> CD pro* will move to C:\Program Files

    Change the Current Drive

    Enter the drive letter followed by a colon

    C:> E:

    E:>

    To change drive and directory at the same time, use CD with the /D switch

    C:> cd /D E:\utils

    E:\utils\>

    launchctl】 A command-line interface to Apple's launchd manager【linux】


    A command-line interface to Apple's launchd manager

    for launch daemons (system-wide services) and launch agents (per-user programs).

    launchd loads XML-based *.plist files placed in the appropriate locations,

    and runs the corresponding commands according to their defined schedule.

    Activate a user-specific agent to be loaded into launchd

    whenever the user logs in:

    launchctl load ~/Library/LaunchAgents/my_script.plist

    Activate an agent which requires root privileges to run

    and/or should be loaded whenever any user logs in (note the absence of ~ in the path):

    sudo launchctl load /Library/LaunchAgents/root_script.plist

    Activate a system-wide daemon to be loaded

    whenever the system boots up (even if no user logs in):

    sudo launchctl load /Library/LaunchDaemons/system_daemon.plist

    Show all loaded agents/daemons, with the PID if the process they specify is currently running,

    and the exit code returned the last time they ran:

    launchctl list

    Unload a currently loaded agent, e.g. to make changes

    (note: the plist file is automatically loaded into launchd after a reboot and/or logging in):

    launchctl unload ~/Library/LaunchAgents/my_script.plist

    Manually run a known (loaded) agent/daemon, even if it isn’t the right time

    (note: this command uses the agent's label, rather than the filename):

    launchctl start my_script

    Manually kill the process associated with a known agent/daemon, if it's running:

    launchctl stop my_script

    p6doc】 Perl 6 documentation【Perl】


    Build index

    p6doc build

    to get information about the function

    p6doc -f slurp

    if the function name is ambiguous use it with the class name

    p6doc -f Type::IO.slurp

    func】 【cpp】


    a simple function

    void functionName() {}

    function with parameters of integers

    void functionName(int param1, int param2) {}

    return type declaration

    int functionName() {

        return 420;

    }

    Return multiple values at once

    (C++ uses pairs [ 2 values ] and tuple [ more than 2 values ])

    Please refer pairs and tuple respectively for more information

    std::tuple functionName() {

        return std::make_tuple( double1, double2 );

    }

    pair result = functionName();

    std::cout << result.first << std::endl;

    std::cout << result.second << std::endl;

    Pass by reference (the caller and the callee use the same variable for the parameter)

    int functionName(int &referenceName) {}

    Pass by value (the caller and callee have two independent variables with the same value)

    int functionName(int valueName) {}

    func】 function【python】


    Simple function

    def functionName():

        return True

    Function with parameters

    def functionName(a, b):

        if a < b:

            return a

        else:

            return b

    Return multiple values

    def functionName(a, b, c):

        return a, b, c # Returns a tuple

        return {'return_a':a, 'return_b':b ,'return_c':c } # Returns a dictionary

    Function with default parameters

    def functionName(a=0, b=1):

        print(a, b)

    functionName() # 0 1

    functionName(3) # 3 1

    functionName(3, 4) # 3 4

    Calling parameters by name

    def functionName(a, b, c):

        print(a, b, c)

    functionName(0, 1, 2) # 0 1 2

    functionName(a=2, c=3, b=4) # 2 4 3

    functionName(2, 3, c=4) # 2 3 4

    Arbitrary number of parameters

    def functionName(*args):

        ...

    functionName(*[1, 2]) # Equivalent of functionName(1, 2)

    functionName(*[1, 2, 3]) # Equivalent of functionName(1, 2, 3)

    Arbitrary number of parameters with arbitrary name

    def functionName(kwargs):

        ...

    functionName({'a' : 3, 'b' : 4}) # Equivalent of functionName(a=3, b=4)

    dhclient】 【linux】


    To release the current IP address:

    sudo dhclient -r

    To obtain a new IP address:

    sudo dhclient

    Running the above in sequence is a common way of refreshing an IP.

    To obtain a new IP address for a specific interface:

    sudo dhclient eth0

    cleanmgr】 Automated cleanup of Temporary files, Internet files, downloaded files, recycle bin. 【win】


    Syntax

          CLEANMGR [/d driveletter] option

          CLEANMGR [/d driveletter] /sageset:n option

          CLEANMGR [/d driveletter] /sagerun:n option

    Options

           /D driveletter The drive that you want Disk Cleanup to clean.

                           NOTE: The /d option is not utilized with /SAGERUN:n.

                           Specify the %systemroot% drive to see all the available options.

           /SAGESET:n Display the Disk Cleanup Settings dialog box and create

                           a registry key to store the settings you select.

                           REQUIRES ELEVATION

                           The n value is stored in the registry and allows you to

                           specify different tasks for Disk Cleanup to run.

                           n can be any integer from 0 to 9999.

           /SAGERUN:n Run task 'n'

                           All drives in the computer will be enumerated, and the

                           selected profile will be run against each drive.

           /TUNEUP:n Run /sageset and /sagerun for the same n

           /LOWDISK Disk Cleanup will open with all options checked.

                           Normally invoked when Windows notifies that of disk space is running out.

           /VERYLOWDISK Disk Cleanup will open with all options checked, no user prompts.

           /SETUP Analyze the system files left over from a previous Windows version. [Undocumented]

           /Autoclean Analyze the system files left over from a previous Windows version/in-place upgrade.

                           and also remove those files automatically. [Undocumented]

           /HELP Display help

           /USAGE Display help

           /? Display help

    If CLEANMGR is run without /sageset or /sagerun, it will start by calculating how much disk space could be saved. This makes the process slower to startup.

    Although many of these files are often described as "junk" you should carefully evaluate what they do before deleting them. By default only the Downloaded Program Files and Temporary Internet Files will be selected.

    Having a hard drive that is over 75% - 80% full will affect performance because file fragmentation (and automatic defragmentation) will increase. Also assuming you have the default 'system managed size' for the page file, that will automatically shrink to fit in the available space. For a drive that has more than 25% free space, deleting files will not make any difference to performance.

    Some cleanup options require elevation, when run without elevation the GUI will include an option [Clean up System Files] which will relaunch CLEANMGR in Elevated mode. When necessary CLEANMGR can take ownership of the files before deleting them.

    To enable Cleanmgr on older servers of Windows Server, open Server Manager and choose Add feature, then select "Desktop Experience"

    After running cleanmgr on a server you may want to disable "Desktop Experience" again.

    Cleanup Settings: Files to delete

        The following options can be toggled on or off when running /SAGESET:n

        Branch Cache

        Catalog Files for the Content Indexer

        Compress Old Files

        Delivery Optimization Files

        Diagnostic data viewer database files

        DirectX Shader cache

        Downloads (Personal downloads folder)

        Downloaded Program Files *

        Language resources Files

        Offline Files

        Old Chkdsk Files

        Recycle Bin * (empties the recycle bin to recover the disc space)

        Retail Demo Offline Content

        Setup Log files

        System Error memory dump files

        System Error minidump files

        Temporary Files

        Temporary Internet Files *

        Temporary Setup Files

        Temporary Offline Files

        Thumbnails

        Update package Backup Files

        User file history

        Windows Defender Antivirus

        Windows error reports and feedback diagnostics

        Windows Update Cleanup

        Windows Upgrade log files

        Items marked with * have a [View Files] option in the GUI to view the individual files.

        The Recycle Bin and Catalog Files for the Content Indexer may appear for more than one drive.

    Application Data

        The user's 'Application Data' folder is not available for cleanup in the above list. Many files in Application Data hold system data that should not be deleted. However if you have an application that leaves a significant number of temporary/junk files in App Data, these can be selectively removed from a roaming profile with a VBScript like this.

    Recent files

        The 'User Profile/Recent Items' folder can contain many more shortcuts than are useful. A very large number of these can affect logon/logoff times. To clear out the shortcuts:

        CD %userprofile%\AppData\Roaming\Microsoft\Windows\Recent

        Echo y| del *.*

    Close Locked files by restarting Windows Explorer

        Save the following batch script:

        @Echo off

        Taskkill /f /im Explorer.exe

        Start Explorer.exe

        Exit

        Then to restart Windows Explorer, just run the batch file.

    Registry

        Registry settings for CLEANMGR are held in:

        [HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches]

        Here are a set of registry entries to turn on a typical selection of cleanmgr options, these can be used with REG or Regedit to pre-populate the regisitry as a scriptable alternative to running /SAGESET

    Log files for CLEANMGR are stored in:

    C:\Windows\System32\LogFiles\setupcln\

    Examples

    Choose a set of options for cleanup (this will display the GUI) and Save as settings group #64:

     CLEANMGR /sageset:64

    Run the saved settings group #64

     CLEANMGR /sagerun:64

    To run Disk Cleanup this way regularly, you can create a shortcut which can be run from the Windows Startup folder or via a regular schedule. To run the saved settings group #64

    %systemroot%\system32\cmd.exe /c CLEANMGR /sagerun:64

    generic】 【redis】


    Delete a key

    DEL key [key ...]

    Return a serialized version of the value stored at the specified key.

    DUMP key

    Determine if a key exists

    EXISTS key [key ...]

    Set a key's time to live in seconds

    EXPIRE key seconds

    Set the expiration for a key as a UNIX timestamp

    EXPIREAT key timestamp

    Find all keys matching the given pattern

    KEYS pattern

    Atomically transfer a key from a Redis instance to another one.

    MIGRATE host port key|"" destination-db timeout [COPY] [REPLACE] [KEYS key [key ...]]

    Move a key to another database

    MOVE key db

    Inspect the internals of Redis objects

    OBJECT subcommand [arguments [arguments ...]]

    Remove the expiration from a key

    PERSIST key

    Set a key's time to live in milliseconds

    PEXPIRE key milliseconds

    Set the expiration for a key as a UNIX timestamp specified in milliseconds

    PEXPIREAT key milliseconds-timestamp

    Get the time to live for a key in milliseconds

    PTTL key

    Return a random key from the keyspace

    RANDOMKEY

    Rename a key

    RENAME key newkey

    Rename a key, only if the new key does not exist

    RENAMENX key newkey

    Create a key using the provided serialized value, previously obtained using DUMP.

    RESTORE key ttl serialized-value [REPLACE]

    Sort the elements in a list, set or sorted set

    SORT key [BY pattern] [LIMIT offset count] [GET pattern [GET pattern ...]] [ASC|DESC] [ALPHA] [STORE destination]

    Alters the last access time of a key(s). Returns the number of existing keys specified.

    TOUCH key [key ...]

    Get the time to live for a key

    TTL key

    Determine the type stored at key

    TYPE key

    Delete a key asynchronously in another thread. Otherwise it is just as DEL, but non blocking.

    UNLINK key [key ...]

    Wait for the synchronous replication of all the write commands sent in the context of the current connection

    WAIT numslaves timeout

    Incrementally iterate the keys space

    SCAN cursor [MATCH pattern] [COUNT count]

    bcdedit】 Manage Boot Configuration Data (BCD) data stores【win】


    Syntax

          BCDEdit /Command [Argument1] [Argument2] ...

    Key

          /? commmand To display detailed help for a particular command, run bcdedit /? command,

                        where command is the name of the command you are searching for more information about.

                        e.g. bcdedit /? createstore

       Store commands:

          /createstore Creates a new empty boot configuration data store.

                        The created store is not a system store.

          /export Export the contents of the system store into a file.

                        This file can be used later to restore the state of the system store.

                        Valid only for the system store.

          /import Restore the state of the system store by using a backup data file

                        previously generated with /export.

                        This command deletes any existing entries in the system store before

                        the import takes place. Valid only for the system store.

          /store This option can be used with most BCDedit commands to specify

                        the store to be used. If this option is not specified, then

                        BCDEdit operates on the system store.

                        Running the bcdedit /store command by itself is equivalent to running

                        the bcdedit /enum active command.

          /sysstore Set the system store device. This only affects EFI-based systems.

                        It does not persist across reboots, and is only used in cases where the system

                        store device is ambiguous.

       Operating on entries in a store:

          /copy Make a copy of a specified boot entry in the same system store.

          /create Create a new entry in the boot configuration data store.

                        If a well-known identifier is specified, then the /application, /inherit, and

                        /device options cannot be specified. If an identifier is not specified or not well

                        known, an /application, /inherit, or /device option must be specified.

          /delete Delete an element from a specified entry.

          /mirror Create a mirror of entries in the store.

       Changing entry options:

          /deletevalue Delete a specified element from a boot entry.

          /set Set an entry option value.

       List current settings:

          /enum [type | id] [/v]

                        List entries in a store.

                        Types: ACTIVE, FIRMWARE, BOOTAPP, BOOTMGR, OSLOADER, RESUME, INHERIT, ALL

                        The /enum option is the default value for BCEdit, so running

                        the bcdedit command without options is equivalent to running the bcdedit /enum active command.

          /v Verbose mode.

                        Usually, any well-known entry identifiers are represented by their friendly shorthand form.

                        Specifying /v as a command-line option displays all identifiers in full.

                        Running the bcdedit /v command by itself is equivalent to running the bcdedit /enum active /v command.

       Controlling the boot manager:

          /bootsequence Specifies a one-time display order to be used for the next boot.

                        This command is similar to the /displayorder option, except that it is used only the

                        next time the computer starts. Afterwards, the computer reverts to the original

                        display order.

          /default Specifies the default entry that the boot manager selects when the timeout expires.

          /displayorder Specifies the display order that the boot manager uses when displaying boot options

                        to a user.

          /timeout Specifies the time to wait, in seconds, before the boot manager selects the default entry.

          /toolsdisplayorder Specifies the display order for the boot manager to use when displaying the Tools menu.

       Emergency Management Services options:

          /bootems Enable or disable Emergency Management Services (EMS) for the specified entry.

          /ems Enable or disable EMS for the specified operating system boot entry.

          /emssettings Set the global EMS settings for the computer.

                        /emssettings does not enable or disable EMS for any particular boot entry.

       Debugging:

          /bootdebug Enable or disable the boot debugger for a specified boot entry.

                        Although this command works for any boot entry, it is effective only for boot applications.

          /dbgsettings Specifies or displays the global debugger settings for the system.

                        This command does not enable or disable the kernel debugger; use the /debug option for

                        that purpose. To set an individual global debugger setting, use the

                        bcdedit /setdbgsettings type value command.

          /debug Enable or disable the kernel debugger for a specified boot entry.

          /hypervisorsettings Set the hypervisor parameters.

       Undocumented:

          /loglevel level [/raw]

                     level is one of the following:

                         t : trace (stdout)

                         i : info (stdout)

                         w : warning (stderr)

                         e : error (stderr)

                     /raw : Display extra details for the device and osdevice fields.

                     Normal display:

                     device partition=\Device\HarddiskVolume2

                     osdevice partition=C:

                     With /raw

                     device PartEx 2800000 HD MBR Sig:151767d7

                     osdevice PartEx 3ed200000 HD MBR Sig:151767d7

    This command will enable the system to trust Windows Insider Preview builds that are signed with certificates that are not trusted by default:

    Bcdedit /set {bootmgr} flightsigning on

    Bcdedit /set flightsigning on

    Reboot after running the command.

    To turn off flightsigning:

    Bcdedit /set {bootmgr} flightsigning off

    Bcdedit /set flightsigning off

    skipcpio】 【linux】


    extract initrd/initramfs in current directory

    /usr/lib/dracut/skipcpio /boot/initramfs-$(uname -r).img | zcat | cpio -ivd

    MegaCli】 【linux】


    MegaCli introduced by LSI as a command line administration of LSI MegaRaid controllers.

    With megacli we can create physical raids, gather info about raids and monitor raids.

    Install MegaCLI

    yum install MegaCli # CentOS

    apt-get install megacli # Ubuntu

    Controller information

    MegaCli -AdpAllInfo -aALL

    MegaCli -CfgDsply -aALL

    Enclosure information

    MegaCli -EncInfo -aALL

    Virtual drive information

    MegaCli -LDInfo -Lall -aALL

    Physical drive information

    MegaCli -PDList -aALL

    MegaCli -PDInfo -PhysDrv [E:S] -aALL

    Battery backup information

    MegaCli -AdpBbuCmd -aALL

    curl】 Transfer data from or to a server, using one of the supported protocols【win】


    Syntax

          curl [options...] url

    Options:

    These options are 'Case Sensitive' which is typical for Unix utilities but unusual for Microsoft Windows.

         --abstract-unix-socket path Connect via abstract Unix domain socket

         --anyauth Pick any authentication method

     -a, --append Append to target file when uploading

         --basic Use HTTP Basic Authentication

     -A, --user-agent name Send User-Agent name to server

         --cacert CA certificate CA certificate to verify peer against

         --capath dir CA directory to verify peer against

     -B, --use-ascii Use ASCII/text transfer

     -E, --cert certificate[:password] Client certificate file and password

         --cert-status Verify the status of the server certificate

         --cert-type type Certificate file type (DER/PEM/ENG)

         --ciphers SSL ciphers to use

         --compressed Request compressed response

     -K, --config file Read config from a file

         --connect-timeout seconds Maximum time allowed for connection

         --connect-to HOST1:PORT1:HOST2:PORT2 Connect to host

     -C, --continue-at offset Resumed transfer offset

     -b, --cookie data Send cookies from string/file

     -c, --cookie-jar filename Write cookies to filename after operation

         --create-dirs Create necessary local directory hierarchy

         --crlf Convert LF to CRLF in upload

         --crlfile file Get a CRL list in PEM format from the given file

     -d, --data data HTTP POST data

         --data-ascii data HTTP POST ASCII data

         --data-binary data HTTP POST binary data

         --data-raw data HTTP POST data, '@' allowed

         --data-urlencode data HTTP POST data url encoded

         --delegation LEVEL GSS-API delegation permission

         --digest Use HTTP Digest Authentication

     -q, --disable Disable .curlrc

         --disable-eprt Inhibit using EPRT or LPRT

         --disable-epsv Inhibit using EPSV

         --dns-interface interface Interface to use for DNS requests

         --dns-ipv4-addr address IPv4 address to use for DNS requests

         --dns-ipv6-addr address IPv6 address to use for DNS requests

         --dns-servers addresses DNS server addrs to use

     -D, --dump-header filename Write the received headers to filename

         --egd-file file EGD socket path for random data

         --engine name Crypto engine to use

         --expect100-timeout seconds How long to wait for 100-continue

     -f, --fail Fail silently (no output at all) on HTTP errors

         --fail-early Fail on first transfer error, do not continue

         --false-start Enable TLS False Start

     -F, --form name=content Specify HTTP multipart POST data

         --form-string name=string Specify HTTP multipart POST data

         --ftp-account data Account data string

         --ftp-alternative-to-user command String to replace USER [name]

         --ftp-create-dirs Create the remote dirs if not present

         --ftp-method method Control CWD usage

         --ftp-pasv Use PASV/EPSV instead of PORT

     -P, --ftp-port address Use PORT instead of PASV

         --ftp-pret Send PRET before PASV

         --ftp-skip-pasv-ip Skip the IP address for PASV

         --ftp-ssl-ccc Send CCC after authenticating

         --ftp-ssl-ccc-mode active/passive Set CCC mode

         --ftp-ssl-control Require SSL/TLS for FTP login, clear for transfer

     -G, --get Put the post data in the URL and use GET

     -g, --globoff Disable URL sequences and ranges using {} and []

     -I, --head Show document info only

     -H, --header header/@file Pass custom header(s) to server

     -h, --help This help text

         --hostpubmd5 md5 Acceptable MD5 hash of the host public key

     -0, --http1.0 Use HTTP 1.0

         --http1.1 Use HTTP 1.1

         --http2 Use HTTP 2

         --http2-prior-knowledge Use HTTP 2 without HTTP/1.1 Upgrade

         --ignore-content-length Ignore the size of the remote resource

     -i, --include Include protocol response headers in the output

     -k, --insecure Allow insecure server connections when using SSL

         --interface name Use network INTERFACE (or address)

     -4, --ipv4 Resolve names to IPv4 addresses

     -6, --ipv6 Resolve names to IPv6 addresses

     -j, --junk-session-cookies Ignore session cookies read from file

         --keepalive-time seconds Interval time for keepalive probes

         --key key Private key file name

         --key-type type Private key file type (DER/PEM/ENG)

         --krb level Enable Kerberos with security level

         --libcurl file Dump libcurl equivalent code of this command line

         --limit-rate speed Limit transfer speed to RATE

     -l, --list-only List only mode

         --local-port num/range Force use of RANGE for local port numbers

     -L, --location Follow redirects

         --location-trusted Like --location, and send auth to other hosts

         --login-options options Server login options

         --mail-auth address Originator address of the original email

         --mail-from address Mail from this address

         --mail-rcpt address Mail from this address

     -M, --manual Display the full manual

         --max-filesize bytes Maximum file size to download

         --max-redirs num Maximum number of redirects allowed

     -m, --max-time time Maximum time allowed for the transfer

         --metalink Process given URLs as metalink XML file

         --negotiate Use HTTP Negotiate (SPNEGO) authentication

     -n, --netrc Must read .netrc for user name and password

         --netrc-file filename Specify FILE for netrc

         --netrc-optional Use either .netrc or URL

     -:, --next Make next URL use its separate set of options

         --no-alpn Disable the ALPN TLS extension

     -N, --no-buffer Disable buffering of the output stream

         --no-keepalive Disable TCP keepalive on the connection

         --no-npn Disable the NPN TLS extension

         --no-sessionid Disable SSL session-ID reusing

         --noproxy no-proxy-list List of hosts which do not use proxy

         --ntlm Use HTTP NTLM authentication

         --ntlm-wb Use HTTP NTLM authentication with winbind

         --oauth2-bearer token OAuth 2 Bearer Token

     -o, --output file Write to file instead of stdout

         --pass phrase Pass phrase for the private key

         --path-as-is Do not squash .. sequences in URL path

         --pinnedpubkey hashes FILE/HASHES Public key to verify peer against

         --post301 Do not switch to GET after following a 301

         --post302 Do not switch to GET after following a 302

         --post303 Do not switch to GET after following a 303

         --preproxy [protocol:]host[:port] Use this proxy first

     -#, --progress-bar Display transfer progress as a bar

         --proto protocols Enable/disable PROTOCOLS

         --proto-default protocol Use PROTOCOL for any URL missing a scheme

         --proto-redir protocols Enable/disable PROTOCOLS on redirect

     -x, --proxy [protocol:]host[:port] Use this proxy

         --proxy-anyauth Pick any proxy authentication method

         --proxy-basic Use Basic authentication on the proxy

         --proxy-cacert file CA certificate to verify peer against for proxy

         --proxy-capath dir CA directory to verify peer against for proxy

         --proxy-cert cert[:passwd] Set client certificate for proxy

         --proxy-cert-type type Client certificate type for HTTS proxy

         --proxy-ciphers list SSL ciphers to use for proxy

         --proxy-crlfile file Set a CRL list for proxy

         --proxy-digest Use Digest authentication on the proxy

         --proxy-header header/@file Pass custom header(s) to proxy

         --proxy-insecure Do HTTPS proxy connections without verifying the proxy

         --proxy-key key Private key for HTTPS proxy

         --proxy-key-type type Private key file type for proxy

         --proxy-negotiate Use HTTP Negotiate (SPNEGO) authentication on the proxy

         --proxy-ntlm Use NTLM authentication on the proxy

         --proxy-pass phrase Pass phrase for the private key for HTTPS proxy

         --proxy-service-name name SPNEGO proxy service name

         --proxy-ssl-allow-beast Allow security flaw for interop for HTTPS proxy

         --proxy-tlsauthtype type TLS authentication type for HTTPS proxy

         --proxy-tlspassword string TLS password for HTTPS proxy

         --proxy-tlsuser name TLS username for HTTPS proxy

         --proxy-tlsv1 Use TLSv1 for HTTPS proxy

     -U, --proxy-user user:password Proxy user and password

         --proxy1.0 host[:port] Use HTTP/1.0 proxy on given port

     -p, --proxytunnel Operate through a HTTP proxy tunnel (using CONNECT)

         --pubkey key SSH Public key file name

     -Q, --quote Send command(s) to server before transfer

         --random-file file File for reading random data from

     -r, --range range Retrieve only the bytes within RANGE

         --raw Do HTTP "raw"; no transfer decoding

     -e, --referer URL Referrer URL

     -J, --remote-header-name Use the header-provided filename

     -O, --remote-name Write output to a file named as the remote file

         --remote-name-all Use the remote file name for all URLs

     -R, --remote-time Set the remote file's time on the local output

     -X, --request command Specify request command to use

         --request-target Specify the target for this request

         --resolve host:port:address Resolve the host+port to this address

         --retry num Retry request if transient problems occur

         --retry-connrefused Retry on connection refused (use with --retry)

         --retry-delay seconds Wait time between retries

         --retry-max-time seconds Retry only within this period

         --sasl-ir Enable initial response in SASL authentication

         --service-name name SPNEGO service name

     -S, --show-error Show error even when -s is used

     -s, --silent Silent mode

         --socks4 host[:port] SOCKS4 proxy on given host + port

         --socks4a host[:port] SOCKS4a proxy on given host + port

         --socks5 host[:port] SOCKS5 proxy on given host + port

         --socks5-basic Enable username/password auth for SOCKS5 proxies

         --socks5-gssapi Enable GSS-API auth for SOCKS5 proxies

         --socks5-gssapi-nec Compatibility with NEC SOCKS5 server

         --socks5-gssapi-service name SOCKS5 proxy service name for GSS-API

         --socks5-hostname host[:port] SOCKS5 proxy, pass host name to proxy

     -Y, --speed-limit speed Stop transfers slower than this

     -y, --speed-time seconds Trigger 'speed-limit' abort after this time

         --ssl Try SSL/TLS

         --ssl-allow-beast Allow security flaw to improve interop

         --ssl-no-revoke Disable cert revocation checks (WinSSL)

         --ssl-reqd Require SSL/TLS

     -2, --sslv2 Use SSLv2

     -3, --sslv3 Use SSLv3

         --stderr Where to redirect stderr

         --suppress-connect-headers Suppress proxy CONNECT response headers

         --tcp-fastopen Use TCP Fast Open

         --tcp-nodelay Use the TCP_NODELAY option

     -t, --telnet-option opt=val Set telnet option

         --tftp-blksize value Set TFTP BLKSIZE option

         --tftp-no-options Do not send any TFTP options

     -z, --time-cond time Transfer based on a time condition

         --tls-max VERSION Use TLSv1.0 or greater

         --tlsauthtype type TLS authentication type

         --tlspassword TLS password

         --tlsuser name TLS user name

     -1, --tlsv1 Use TLSv1.0 or greater

         --tlsv1.0 Use TLSv1.0

         --tlsv1.1 Use TLSv1.1

         --tlsv1.2 Use TLSv1.2

         --tlsv1.3 Use TLSv1.3

         --tr-encoding Request compressed transfer encoding

         --trace file Write a debug trace to FILE

         --trace-ascii file Like --trace, but without hex output

         --trace-time Add time stamps to trace/verbose output

         --unix-socket path Connect through this Unix domain socket

     -T, --upload-file file Transfer local FILE to destination

         --url url URL to work with

     -B, --use-ascii Use ASCII/text transfer

     -u, --user user:password Server user and password

     -A, --user-agent name Send User-Agent name to server

     -v, --verbose Make the operation more talkative

     -V, --version Show version number and quit

     -w, --write-out format Use output FORMAT after completion

         --xattr Store metadata in extended file attributes

    curl is a powerful tool, please use it responsibly.

    Examples

    The example.com domain is used for these examples, it contains simple demonstration text and allows both HTTP and HTTPS connections.

    Retrieve a web page, display the status code and all the raw content of the page:

    C:\> curl https:example.com

    StatusCode : 200

    StatusDescription : OK

    Content :

                        ...

    Retrieve a web page, display the status code and header information only:

    C:\> curl -I https:example.com

    HTTP /1.1 200 OK

    Content-Encoding: gzip

    ...

    Retrieve a web page, passing a specific User-Agent HTTP header (some websites use this to sniff the browser used):

    C:\> curl -A "Mozilla FireFox(72.0)" https:example.com

    Download the home page of example.com as a file (testing.html):

    C:\> curl -o C:\demo\testing.html https:example.com/

    Retrieve a file listing from an FTP server (null password):

    C:\> curl ftp:anonymous@speedtest.tele2.net

    caffeinate】 Prevent a system from sleeping (Mac OS X)【linux】


    Prevent mac from sleeping for 1 hour (3600 seconds):

    caffeinate -u -t 3600

    Prevent mac from sleeping until a command completes:

    caffeinate -s command

    call】 Call one batch program from another, or call a subroutine【win】


    Syntax

          CALL [drive:][path]filename [parameters]

          CALL :label [parameters]

          CALL internal_cmd

    Key:

       pathname The batch program to run.

       parameters Any command-line arguments.

       :label Jump to a label in the current batch script.

       internal_cmd Run an internal command, first expanding any variables in the argument.

    The Microsoft help for the CALL command states: "Calls one batch program from another without stopping the parent batch program" to expand on this, it is true that the parent does not STOP, but it does PAUSE while the second script runs.

    CALL a second batch file

        The CALL command will launch a new batch file context along with any specified parameters. When the end of the second batch file is reached (or if EXIT is used), control will return to just after the initial CALL statement.

        Arguments can be passed either as a simple string or using a variable:

        CALL MyScript.cmd "1234"

        CALL OtherScript.cmd %_MyVariable%

        Example

        ::----------start main.cmd-----------

        @Echo off

        CALL function.cmd 10 first

        Echo %_description% - %_number%

        CALL function.cmd 15 second

        Echo %_description% - %_number%

        ::----------end main.cmd-------------

        ::----------start function.cmd---------

        @Echo off

        :: Add 25 to %1

        SET /a _number=%1 + 25

        :: Store %2

        SET _description=[%2]

        ::----------end function.cmd-----------

        In many cases you will also want to use SETLOCAL and ENDLOCAL to keep variables in different batch files completely separate, this will avoid any potential problems if two scripts use the same variable name.

        If you execute a second batch file without using CALL you may run into some buggy behaviour: if both batch files contain a label with the same name and you have previously used CALL to jump to that label in the first script, you will find execution of the second script starts at the same label. Even if the second label does not exist this will still raise an error "cannot find the batch label". This bug can be avoided by always using CALL.

    CALL a subroutine (:label)

        The CALL command will pass control to the statement after the label specified along with any specified parameters.

        To exit the subroutine specify GOTO:eof this will transfer control to the end of the current subroutine.

        A label is defined by a single colon followed by a name:

        :myShinyLabel

        If placed inside brackets, the label must be followed by at least one valid command, even just an ECHO or REM command.

        The maximum length for a label is 127 characters, no spaces.

        This is the basis of a batch file function.

        CALL :sub_display 123

        CALL :sub_display 456

        ECHO All Done

        GOTO :eof

        :sub_display

        ECHO The result is %1

        EXIT /B

        At the end of the subroutine an EXIT /B will return to the position where you used CALL

        (GOTO :eof can also be used for this)

    Call and optionally continue

        In some cases you may want to call a second batch file (or subroutine) and continue only if it succeeded.

        CALL SecondScript.cmd || goto :eof

        This will goto:eof if SecondScript.cmd returns an errorlevel greater than zero, you can force an errorlevel by using Exit /b 1

    Passing by Reference

        In addition to passing numeric or string values on the command line, it is also possible to pass a variable name and then use the variable to transfer data between scripts or subroutines. Passing by reference is a slightly more advanced technique but can be essential if the string contains characters that are CMD delimiters or quotes, otherwise passing a string like Start & middle:"and & End is likely to break something.

        @Echo off

        Echo:

        Set "var1=Red Pippin"

        Set "var2=St Edmunds Pippin"

        Set "var3=Egremont Russet"

        Echo: before: var1=%var1% var2=%var2% var3=%var3%

        call :myGetFunc var1 var2 var3

        Echo: after: var1=%var1% var2=%var2% var3=%var3%

        Echo:&pause&goto:eof

        ::----------------------------------------------

        ::-- Function section starts below

        ::----------------------------------------------

        :myGetFunc - passing a variable by reference

        Set "%~1=return64"

        Set "%~3=return65"

        EXIT /B

    Buggy behaviour when using CALL

        Redirection via a pipe '|' does not always work as expected.

        This will work:

        CALL :function >file.txt

        This will fail:

        CALL :function | more

        More details can be found in this SO question: Why does delayed expansion fail when inside a piped block of code?

        If the CALL command contains a caret character within a quoted string "test^ing" , the carets will be doubled.

    Advanced usage : CALLing internal commands

        CALL command [command_parameters]

        CALL can also be used to run any internal command (SET, ECHO etc) with the exception of FOR and IF.

        CALL will expand any variables passed on the same line. CALL REM only partly works: redirection operators, conditional execution operators and brackets will be not remarked.

        This is undocumented behaviour, in fact whenever CALL is run without a : prefix, it will always search disk for a batch file/executable called command before running the internal command. The effect of this extra disc access is that CALL SET is significantly slower than CALL, its use in loops or with a large number of variables should be avoided.

        Example

         @Echo off

         SETLOCAL

         set _server=frodo

         set _var=_server

         CALL SET _result=%%%_var%%%

         echo %_result%

        The line shown in bold has the '%' symbols tripled, CALL will expand this to: SET _result=frodo

        Each CALL does one substitution of the variables. (You can also do CALL CALL... for multiple substitutions)

        In many cases, DelayedExpansion is a better/faster method:

         @Echo Off

         Setlocal EnableDelayedExpansion

         Set _server=frodo

         Set _var=_server

         Set _result=!%_var%!

         Echo %_result%

    Errorlevels

        If you run CALL SET this will reset ERRORLEVEL = 0 even though normally SET ... will fail to reset an ERRORLEVEL

        If you CALL a subroutine, the ERRORLEVEL will be left unchanged

        If you CALL a subroutine, with a label that does not exist ERRORLEVEL will be set to 1

        (call ) will set the ERRORLEVEL to 0.

        (call) will set the ERRORLEVEL to 1.

    If you CALL an executable or resource kit utility make sure it's available on the machine where the batch will be running, test for it's existence with an IF command and throw an error if missing.

    CALL is an internal command, (internally it is closely related to GOTO).

    If Command Extensions are disabled, the CALL command will not accept batch labels.

    bootrec】 Repair or replace a partition boot sector(Win RE)【win】


    Syntax

          BOOTREC /FIXMBR Write an MBR to the system partition.

          BOOTREC /FIXBOOT Writes a new boot sector onto the system partition.

          BOOTREC /SCANOS Scans all disks for Windows installations and display entries not currently in the BCD store.

          BOOTREC /REBUILDBCD Scans all disks for Windows installations and provide a choice of which entries to add to the BCD store.

    /FixMbr does not overwrite the existing partition table. Use this option when you must resolve MBR corruption issues, or when you have to remove nonstandard code from the MBR.

    Use /FixBoot if The boot sector was damaged or replaced.

    Examples

    Use Bootrec.exe to troubleshoot a "Bootmgr Is Missing" error.

    If rebuilding the BCD store doesn't resolve the startup issue, you can export and delete the BCD store and then run this option again. By doing this, you make sure that the BCD store is completely rebuilt. To do this, type the following commands at the Windows RE command prompt:

    bcdedit /export C:\BCD_Backup

    c:

    cd boot

    attrib bcd -s -h -r

    ren c:\boot\bcd bcd.old

    bootrec /RebuildBcd

    scsi_logging_level】 set and get the SCSI logging level (install sg3-utils)【linux】


    configure the log level of several tracepoints along the Linux SCSI stack

    scsi_logging_level -s --ioctl=7

    track SCSI commands as they flow through

    the SCSI submission and completion path

    (call dmesg after that)

    scsi_logging_level -s --midlevel=7

    DevCon】 Device Manager【win】


    Syntax

          devcon.exe [-r] [-m:\machine] command [arg...]

          devcon.exe help command

    Key

       -r Reboot the machine after command is complete, if needed.

       machine Name of target machine.

       command The command to perform (see below).

       arg... One or more arguments if required by command.

    Commands:

      classfilter Allow modification of class filters.

      classes List all device setup classes.

      disable Disable devices that match the specific hardware/instance ID.

      driverfiles List driver files installed for devices.

      drivernodes List all the driver nodes of devices.

      enable Enable devices that match the specific hardware/instance ID.

      find Find devices that match the specific hardware/instance ID.

      findall Find devices including those that are not present.

      help Display this information.

      hwids List hardware ID's of devices.

      install Manually install a device.

      listclass List all devices for a setup class.

      reboot Reboot local machine.

      remove Remove devices that match the specific hardware/instance ID.

      rescan Scan for new hardware.

      resources List hardware resources of devices.

      restart Restart devices that match the specific hardware/instance ID.

      stack List expected driver stack of devices.

      status List running status of devices.

      update Manually update a device.

      UpdateNI Manually update a device without user prompt

      SetHwID Add, delete, and change the order of hardware IDs of root-enumerated devices.

    DevCon is not redistributable. It is provided for use as a debugging and development tool.

    Examples

    List all known PCI devices on the computer pc64.

    devcon -m:\pc64 find pci*

    Install a new instance of the Microsoft loopback adaptor and restart if required. This creates a new root-enumerated device node with which you can install a "virtual device," such as the loopback adaptor.

    devcon -r install %WINDIR%\Inf\Netloop.inf *MSLOOP

    List all known setup classes. Displays both the short name and the descriptive name.

    devcon classes

    Lists files that are associated with each device in the ports setup class.

    devcon driverfiles =ports

    Disable all devices that have a hardware ID that ends in "MSLOOP" (including "*MSLOOP").

    devcon disable *MSLOOP

    List all compatible drivers for the device ROOT\PCI_HAL\PNP0A03. This can be used to determine why an integral device information (.inf) file was chosen, instead of a third-party .inf file.

    devcon drivernodes @ROOT\PCI_HAL\PNP0A03

    Enable all devices that have a hardware ID of "*MSLOOP". The single quotation mark indicates that the hardware ID must be taken literally (in other words, the asterisk ["*"] actually is an asterisk; it is not a wildcard character).

    devcon enable '*MSLOOP

    List device instances of all devices that are present on the local computer.

    devcon find *

    List all known peripheral component interconnect (PCI) devices that are on the local computer (this command assumes that a device is PCI if it has a hardware ID that is prefixed by "PCI\").

    devcon find pci*

    List devices that are a member of the ports setup class and that contain "PNP" in their hardware ID.

    devcon find =ports *pnp*

    List devices that are present that are a member of the ports setup class and that are in the "root" branch of the enum tree (the instance ID is prefixed by "root\"). Note that you should not make any programmatic assumption about how an instance ID is formatted. To determine root devices, you can look at device status bits. This feature is included in DevCon to aid in debugging.

    devcon find =ports @root*

    List "nonpresent" devices and devices that are present for the ports class. This includes devices that have been removed, devices that have been moved from one slot to another and, in some cases, devices that have been enumerated differently due to a BIOS change.

    devcon findall =ports

    List all devices that are present for each class named (in this case, USB and 1394).

    devcon listclass usb 1394

    Remove all USB devices. Devices that are removed are listed with their removal status.

    devcon remove @usb*

    Rescan for new Plug and Play devices.

    devcon rescan

    List the resources that are used by all devices in the ports setup class.

    devcon resources =ports

    Restart the loopback adaptor ROOT*MSLOOP\0000. The single quotation mark in the command indicates that the instance ID must be taken literally.

    devcon restart =net @'ROOT*MSLOOP\0000

    List all hardware IDs of mouse class devices on the system.

    devcon hwids=mouse

    Assign the hardware ID, beep, to the legacy beep device.

    devcon sethwid @ROOT\LEGACY_BEEP\0000 := beep

    List the status of each device present that has an instance ID that begins with "pci\".

    devcon status @pci*

    List the status of an Advanced Configuration and Power Interface (ACPI)-enumerated serial port.

    devcon status @ACPI\PNP0501\1

    List the status of all COM ports.

    devcon status *PNP05*

    Errorlevels returned by DevCon.exe:

    0 = success.

    1 - restart is required.

    2 = failure.

    3 = syntax error.

    systemctl】 【linux】


    List all loaded/active units

    systemctl list-units

    Check the status of a service

    systemctl status foo.service

    Start a service

    systemctl start foo.service

    Restart a service

    systemctl restart foo.service

    Stop a service

    systemctl stop foo.service

    Reload a service's configuration

    systemctl reload foo.service

    Enable a service to startup on boot

    systemctl enable foo.service

    Disable a service to startup on boot

    systemctl disable foo.service

    List the dependencies of a service

    when no service name is specified, lists the dependencies of default.target

    systemctl list-dependencies foo.service

    List currently loaded targets

    systemctl list-units --type=target

    Change current target

    systemctl isolate foo.target

    Change default target

    systemctl enable foo.target

    blktrace】 a block layer IO tracing mechanism which provides detailed information about request queue operations up to user space【linux】


    trace PC (non-filesystem requests, PC) on the /dev/sdb disk.

    blkparse generates human-readable formatting

    blktrace /dev/sdb -a PC -o - | blkparse -i -

    changepk】 Upgrade device Product Key to a supported edition of Windows 10.【win】


    Syntax

          CHANGEPK /ProductKey NewProductKey

    This can be used to move from Home > Pro Education, from Pro > Education, from Pro > Enterprise a full list of the supported Edition upgrades and downgrades is available on docs.microsoft.com

    You can also upgrade using slmgr.vbs and a KMS client setup key.

    Examples

    Upgrade to Windows 10 Enterprise:

    C:\> Cscript.exe c:\windows\system32\slmgr.vbs /ipk NPPR9-FWDCX-D2C8J-H872K-2YT43

    func】 function【golang】


    a simple function

    func functionName() {}

    function with parameters (again, types go after identifiers)

    func functionName(param1 string, param2 int) {}

    multiple parameters of the same type

    func functionName(param1, param2 int) {}

    return type declaration

    func functionName() int {

        return 42

    }

    Can return multiple values at once

    func returnMulti() (int, string) {

        return 42, "foobar"

    }

    var x, str = returnMulti()

    Return multiple named results simply by return

    func returnMulti2() (n int, s string) {

        n = 42

        s = "foobar"

         n and s will be returned

        return

    }

    var x, str = returnMulti2()

    ### Functions As Values And Closures

    func main() {

         assign a function to a name

        add := func(a, b int) int {

            return a + b

        }

         use the name to call the function

        fmt.Println(add(3, 4))

    }

    Closures, lexically scoped: Functions can access values that were

    in scope when defining the function

    func scope() func() int{

        outer_var := 2

        foo := func() int { return outer_var}

        return foo

    }

    func another_scope() func() int{

         won't compile because outer_var and foo not defined in this scope

        outer_var = 444

        return foo

    }

    Closures: don't mutate outer vars, instead redefine them!

    func outer() (func() int, int) {

        outer_var := 2

        inner := func() int {

            outer_var += 99 attempt to mutate outer_var from outer scope

            return outer_var => 101 (but outer_var is a newly redefined

                              variable visible only inside inner)

        }

        return inner, outer_var => 101, 2 (outer_var is still 2, not mutated by foo!)

    }

    ### Variadic Functions

    func main() {

        fmt.Println(adder(1, 2, 3)) 6

        fmt.Println(adder(9, 9)) 18

        nums := []int{10, 20, 30}

        fmt.Println(adder(nums...)) 60

    }

    By using ... before the type name of the last parameter you can indicate that it takes zero or more of those parameters.

    The function is invoked like any other function except we can pass as many arguments as we want.

    func adder(args ...int) int {

        total := 0

        for _, v := range args { Iterates over the arguments whatever the number.

            total += v

        }

        return total

    }

    OCaml】 【ocaml】


    OCaml, originally named Objective Caml, is the main implementation of the programming language Caml.

    A member of the ML language family.

    Compile into a bytecode executable:

    ocamlc hello.ml -o hello

    Compile into an optimized native-code executable:

    ocamlopt hello.ml -o hello

    Start ocaml interactive shell

    ocaml

    Start the shiny frontend to the ocaml interactive shell, utop

    to install it: opam install utop

    utop

    cmd】 Start a new CMD shell and (optionally) run a command/executable program.【win】


    Syntax

          CMD [charset] [options]

          CMD [charset] [options] [/C Command]

          CMD [charset] [options] [/K Command]

    Options

       /C Run Command and then terminate

       /K Run Command and then remain open, at the CMD prompt.

              This is useful for testing, e.g. to examine variables.

       Command : The command, program or batch script to be run.

                 This can even be several commands separated with '&'

                 (the whole should also be surrounded by "quotes")

       /T:fg Sets the foreground/background colours

       /A Output ANSI characters.

       /U Output UNICODE characters (UCS-2 le).

              These options will affect piping or redirecting to a file.

              Most common text files are ANSI, use these switches when

              you need to convert the character set.

       /D Ignore registry AutoRun commands

              HKLM | HKCU \Software\Microsoft\Command Processor\AutoRun

       /E:ON Enable CMD Command Extensions (default)

       /X Enable CMD Command Extensions (old switch for compatibility)

       /E:OFF Disable CMD Command Extensions

       /Y Disable CMD Command Extensions (old switch for compatibility)

       /F:ON Enable auto-completion of pathnames entered at the CMD prompt

       /F:OFF Disable auto-completion of pathnames entered at the CMD prompt (default)

            At the command prompt Ctrl-D gives folder name completion and Ctrl-F gives File and folder name completion.

            These key-strokes will display the first matching path. Thereafter, repeated pressing of the same control key will cycle through the list of matching paths. Pressing SHIFT with the control key will move through the list backwards.

       /Q Turn echo off

       /S Strip " quote characters from command.

             If command starts with a quote, the first and last quote chars in command

             will be removed, whether /s is specified or not.

       /V:ON Enable delayed environment variable expansion

             this allows a FOR loop to specify !variable! instead of %variable%

             expanding the variable at execution time instead of at input time.

       /V:OFF

             Disable delayed environment expansion.

             Delayed Environment expansion can also be set with SETLOCAL

    If /C or /K is specified, then the remainder of the command line is processed as an immediate command in the new shell. Multiple commands separated by the command separator '&' or '&&' are accepted if surrounded by quotes.

    In Windows Explorer, you can type "cmd" in the address bar to open a prompt at the current location.

    For more detail about the CMD shell: QuickEdit, handing quotes, max line length etc, see the CMD Syntax page.

    If you start a second nested CMD shell (or PowerShell), this will be added to the TITLE of the CMD/terminal window, when you EXIT back to the initial shell, the Title will also revert making it possible to track how many nested shells you have open.

    ErrorLevel

        CMD /C will return an errorlevel, for example CMD /c dir Z: where the drive Z: does not exist, will return %errorlevel% = 1 to the calling CMD shell.

    Launching CMD/batch files from a UNC path

        While most command line utilities do fully support UNC paths, they cannot be set as the current directory. Launching a batch file from a UNC path will implicitly run CMD.exe with that UNC path, this will often return the error: path is an invalid current directory path. UNC paths are not supported. Defaulting to Windows directory.

        This can be dangerous if your batch file makes any assumptions about the current directory,

        e.g. if it includes the line DEL *.ico, that will delete .ico files from the Windows directory instead of the folder where the batch file resides.

        If you are confident that the batch file won't be affected by this, you can suppress the error in one of two ways: Add a CLS command as the first line of the batch script, or add the registry key DisableUNCCheck as described in Q156276

        Alternatively start the batch file with pushd "%~dp0"

        That will change directory to your batch file location (%0), and for UNC paths it will auto-create a temporary drive map.

    Launching CMD/batch files from PowerShell

        When calling CMD from PowerShell the --% operator can be used to control when $ symbols and quoted expressions will be interpreted/expanded by PowerShell:

        cmd.exe --% /c dir "C:\financial $accounts\" /w

        Anything to the left of --% will be expanded:

        $folder = 'C:\financial $accounts\'

        cmd.exe /c dir $folder --%/w

    Inheritance

        A new CMD.exe session can be instantiated in several ways, explicitly starting a new CMD session from an existing CMD shell, CALLing a batch file or implicit instantiation caused by piping a command or running a FOR /F command.

        In all these cases, only the environment variable values are inherited by the new CMD session. Delayed expansion state, Command extension state and Echo state will all revert back to the default state based on the registry.

        For more detail on inheritance and expansion see this StackOverflow thread.

    Command Extensions

        Much of the functionality of CMD.exe can be disabled - this will affect all the internal commands, and most dynamic/volatile environment variables (%TIME% , %DATE% , %RANDOM% , %CD% etc)

        Command Extensions are enabled by default.

        This can be changed by setting a value in the registry: HKCU\Software\Microsoft\Command Processor\EnableExtensions

        Command Extensions can also be turned on or off by running CMD /e:on or CMD /e:off

        or run SETLOCAL EnableExtensions (SetLocal will take precedence)

        Forum thread: Checking if command extensions are available.

    Examples

    Run a program and pass a Filename parameter:

    CMD /c write.exe c:\docs\sample.txt

    Run a program and pass a Long Filename:

    CMD /c write.exe "c:\sample documents\sample.txt"

    Spaces in Program Path:

    CMD /c ""c:\Program Files\Microsoft Office\Office\Winword.exe""

    Spaces in Program Path + parameters:

    CMD /c ""c:\Program Files\demo.cmd"" Parameter1 Param2

    Spaces in Program Path + parameters with spaces:

    CMD /k ""c:\batch files\demo.cmd" "Parameter 1 with space" "Parameter2 with space""

    CMD will strip the outer quotes if there is a double quote at the start and end so you can also cheat and write the above as:

    CMD /k @"c:\batch files\demo.cmd" "Parameter 1 with space" "Parameter2 with space"

    Launch Demo1 and then Launch Demo2:

    CMD /c ""c:\Program Files\demo1.cmd" & "c:\Program Files\demo2.cmd""

    curl】 【linux】


    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

    crontab】 time task【linux】


    set a shell

    SHELL=/bin/bash

    crontab format

    - - - - -

    | | | | |

    | | | | +- day of week (0 - 7) (where sunday is 0 and 7)

    | | | +--- month (1 - 12)

    | | +----- day (1 - 31)

    | +------- hour (0 - 23)

    +--------- minute (0 - 59)

    example entries

    every 15 min

    */15 * * * * /home/user/command.sh

    every midnight

    0 0 * * * /home/user/command.sh

    every Saturday at 8:05 AM

    5 8 * * 6 /home/user/command.sh

    scripting】 【redis】


    Execute a Lua script server side

    EVAL script numkeys key [key ...] arg [arg ...]

    Execute a Lua script server side

    EVALSHA sha1 numkeys key [key ...] arg [arg ...]

    Set the debug mode for executed scripts.

    SCRIPT DEBUG YES|SYNC|NO

    Check existence of scripts in the script cache.

    SCRIPT EXISTS sha1 [sha1 ...]

    Remove all the scripts from the script cache.

    SCRIPT FLUSH

    Kill the script currently in execution.

    SCRIPT KILL

    Load the specified Lua script into the script cache.

    SCRIPT LOAD script

    smbclient】 【linux】


    To display public shares on the server:

    smbclient -L -U%

    To connect to a share:

    smbclient / -U%

    dhcpdump】 sniffing and displaying DHCP packets on the network【linux】


    sniff DHCP traffic on interface eth0

    dhcpdump -i eth0

    basics】 【rust】


    Functions

    `i32` is the type for 32-bit signed integers

    fn add2(x: i32, y: i32) -> i32 {

         Implicit return (no semicolon)

        x + y

    }

    Main function

    fn main() {

         Numbers

        

         Immutable bindings

        let x: i32 = 1;

         Integer/float suffixes

        let y: i32 = 13i32;

        let f: f64 = 1.3f64;

         Type inference

         Most of the time, the Rust compiler can infer what type a variable is, so

         you don’t have to write an explicit type annotation.

         Throughout this tutorial, types are explicitly annotated in many places,

         but only for demonstrative purposes. Type inference can handle this for

         you most of the time.

        let implicit_x = 1;

        let implicit_f = 1.3;

         Arithmetic

        let sum = x + y + 13;

         Mutable variable

        let mut mutable = 1;

        mutable = 4;

        mutable += 2;

         Strings

        

         String literals

        let x: &str = "hello world!";

        

         Printing

        println!("{} {}", f, x); 1.3 hello world

        

         A `String` – a heap-allocated string

        let s: String = "hello world".to_string();

        

         A string slice – an immutable view into another string

         This is basically an immutable pair of pointers to a string – it doesn’t

         actually contain the contents of a string, just a pointer to

         the begin and a pointer to the end of a string buffer,

         statically allocated or contained in another object (in this case, `s`)

        let s_slice: &str = &s;

        

        println!("{} {}", s, s_slice); hello world hello world

         Vectors/arrays

        

         A fixed-size array

        let four_ints: [i32; 4] = [1, 2, 3, 4];

        

         A dynamic array (vector)

        let mut vector: Vec = vec![1, 2, 3, 4];

        vector.push(5);

        

         A slice – an immutable view into a vector or array

         This is much like a string slice, but for vectors

        let slice: &[i32] = &vector;

        

         Use `{:?}` to print something debug-style

        println!("{:?} {:?}", vector, slice); [1, 2, 3, 4, 5] [1, 2, 3, 4, 5]

         Tuples

        

         A tuple is a fixed-size set of values of possibly different types

        let x: (i32, &str, f64) = (1, "hello", 3.4);

        

         Destructuring `let`

        let (a, b, c) = x;

        println!("{} {} {}", a, b, c); 1 hello 3.4

        

         Indexing

        println!("{}", x.1); hello

    }

    分类列表:



    腾图小抄 SCWY.net v0.03 小抄561条 自2022-01-02访问318093次