MySQL 导出 xls

若查询语句为

SELECT *,count(*) as count FROM `youhui_activity_log` WHERE `type`="activity_21_page_index" AND `value`="c8" AND DATE_FORMAT(`create_time`,"%Y-%m-%d")= "2018-12-06" GROUP BY `key`;

则导出语句为

SELECT *,count(*) as count FROM `youhui_activity_log` WHERE `type`="activity_21_page_index" AND `value`="c8" AND DATE_FORMAT(`create_time`,"%Y-%m-%d")= "2018-12-06" GROUP BY `key` INTO OUTFILE '/usr/outsql/ac_log_2.xls'; 

MySQL 配置文件添加指定的导出目录

secure_file_priv = E:/

否则可能出现报错:

1290 - The MySQL server is running with the --secure-file-priv option so it cannot execute this statement

导出 SQL 文件

mysqldump -uroot -p wa_data cleancheckrule > /usr/outsql/clean14.sql

一些 JavaScript JS 函数

数组过滤重复值

//数组过滤重复值
function uniqueArr(array) {
  var n = []; //结果数组
  //从第一项开始遍历
  for (var i = 0; i < array.length; i++) {
	//如果当前数组的第i项在当前数组中第一次出现的位置不是i,
	//那么表示第i项是重复的,忽略掉。否则存入结果数组
	if (array.indexOf(array[i]) == i) n.push(array[i]);
  }
  return n;
}

删除空字符换行,过滤表格 text 中多余的空格

function Trim(str,is_global){
  var result;
  result = str.replace(/(^\s+)|(\s+$)/g,"");
  if(is_global && is_global.toLowerCase()=="g"){
	result = result.replace(/\s/g,"");
  }
  return result;
}

JS 中空的判断

alert(0 == ''); //true
alert(0 == false); //true
alert(false == ''); //true
alert(null == undefined); //true

alert(!0); //true
alert(!false); //true
alert(!undefined); //true
alert(!null); //true
alert(!''); //true

alert(0 == undefined); //false
alert(0 == null); //false
alert(false == null); //false
alert(false == undefined);//false
alert('' == null); //false
alert('' == undefined); //false

typeof(undefined) == 'undefined'
typeof(null) == 'object'
typeof("") == 'string'
typeof(0) == 'number'
typeof(false) == 'boolean'

String(undefined) -> "undefined"
String(null) -> "null"
String("") -> ""
String(0) -> "0"
String(false) -> "false"

区分 JS 中的 undefined , null , “” , 0 和 false

https://www.cnblogs.com/yangzhx/p/4019073.html

JS 移除 数组中指定元素

//首先需要找到元素的下标:
var array = [2, 5, 9];
var index = array.indexOf(5);
//使用splice函数进行移除:
if (index > -1) {
    array.splice(index, 1);
}
//splice函数的第二个参数指删除的数目。splice直接修改原数组,并把删除的所有元素以另一个新数组的方式返回。

数字前补零

function PrefixInteger(num, length) {
  return (Array(length).join('0') + num).slice(-length);
}

Toast 弹窗

function Toast(msg,duration){
  duration=isNaN(duration)?3000:duration;
  var m = document.createElement('div');
  m.innerHTML = msg;
  m.style.cssText="width: 60%;min-width: 150px;opacity: 0.7;height: 30px;color: rgb(255, 255, 255);line-height: 30px;text-align: center;border-radius: 5px;position: fixed;top: 40%;left: 20%;z-index: 999999;background: rgb(0, 0, 0);font-size: 12px;";
  document.body.appendChild(m);
  setTimeout(function() {
    var d = 0.5;
    m.style.webkitTransition = '-webkit-transform ' + d + 's ease-in, opacity ' + d + 's ease-in';
    m.style.opacity = '0';
    setTimeout(function() { document.body.removeChild(m) }, d * 1000);
  }, duration);
}

复制文本

//复制文本
function copy (id, attr='innerHTML') {
  let target = null;
  if (attr) {
    target = document.createElement('div');
    target.id = 'tempTarget';
    target.style.opacity = '0';
    if (id) {
      let curNode = document.querySelector('#' + id);
      target.innerText = curNode[attr];
    } else {
      target.innerText = attr;
    }
    document.body.appendChild(target);
  } else {
    target = document.querySelector('#' + id);
  }
  try {
    let range = document.createRange();
    range.selectNode(target);
    window.getSelection().removeAllRanges();
    window.getSelection().addRange(range);
    document.execCommand('copy');
    window.getSelection().removeAllRanges();
    console.log('复制成功:' + range)
  } catch (e) {
    console.log('复制失败')
  }
  if (attr) {
    // remove temp target
    target.parentElement.removeChild(target);
  }
}

获得链接地址的参数

function getQueryString(name,link=''){
  console.log(link)
  var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
  if(link){
    var num=link.indexOf("?");
    link=link.substr(num+1);
    var r = link.match(reg);
  }else{
    var r = window.location.search.substr(1).match(reg);
  }
  if(r!=null)return  unescape(r[2]); return null;
}

HTML 标签获取 图片地址

img_src: function (str){
  var imgReg = /<img.*?(?:>|\/>)/gi;
  var srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i;
  var arr = str.match(imgReg);    
  var list = []
  for(var i = 0; i < arr.length; i++) {
    var src = arr[i].match(srcReg);
    //获取图片地址
    if (src[1]) {
    list.push(src[1])
    }
    //当然你也可以替换src属性
    if (src[0]) {
      var t = src[0].replace(/src/i, "href");
    }
  }
  console.log(list)
  return list;
},

截取文件后缀

file_ext:function (name){
  let fileName = name.lastIndexOf(".");//取到文件名开始到最后一个点的长度
  let fileNameLength = name.length;//取到文件名长度
  let fileFormat = name.substring(fileName + 1, fileNameLength);//截
  console.log(fileFormat);
  return fileFormat
},

不刷新页面修改地址栏

var stateObject = {};
var title = "修改地址";
var newUrl = '/view/fontface4.html';
//修改地址栏中的地址,后退时返回当前页
history.pushState(stateObject, title, newUrl);
//修改地址栏中的地址,后退时返回前一页
history.replaceState(stateObject, title, newUrl);

jQuery Post 跳转

$.extend({
  StandardPost:function(url,args){
    console.log(args)
    var body = $(document.body),
      form = $("<form method='post'></form>"),
      input;
    form.attr({"action":url});
    $.each(args,function(key,value){
      input = $("<input type='hidden'>");
      input.attr({"name":key});
      input.val(value);
      form.append(input);
    });

    form.appendTo(document.body);
    form.submit();
    document.body.removeChild(form[0]);
  }
});
//使用
$.StandardPost(url,{data:'test'});

jQuery 模拟长按

$("#id").on({
  touchstart: function(e) {
    // 长按事件触发
    timeOutEvent = setTimeout(function() {
      timeOutEvent = 0;
      console.log("长按事件")
    }, 1000);
  },
  touchmove: function() {
    clearTimeout(timeOutEvent);
    timeOutEvent = 0;
  },
  touchend: function() {
    clearTimeout(timeOutEvent);
    timeOutEvent = 0;
    return false;
  }
})

指定日期的上个月,下个月

//下个月
const getNextMonth = function(date) {
  var arr = date.split('-');
  var year = arr[0]; //获取当前日期的年份
  var month = arr[1]; //获取当前日期的月份
  var day = arr[2]; //获取当前日期的日
  var days = new Date(year, month, 0);
  days = days.getDate(); //获取当前日期中的月的天数
  var year2 = year;
  var month2 = parseInt(month) + 1;
  if (month2 == 13) {
    year2 = parseInt(year2) + 1;
    month2 = 1;
  }
  var day2 = day;
  var days2 = new Date(year2, month2, 0);
  days2 = days2.getDate();
  if (day2 > days2) {
    day2 = days2;
  }
  if (month2 < 10) {
    month2 = '0' + month2;
  }

  var t2 = year2 + '-' + month2 + '-' + day2;
  return t2;
}
//上个月
const getPreMonth = function (date) {
  var arr = date.split('-');
  var year = arr[0]; //获取当前日期的年份
  var month = arr[1]; //获取当前日期的月份
  var day = arr[2]; //获取当前日期的日
  var days = new Date(year, month, 0);
  days = days.getDate(); //获取当前日期中月的天数
  var year2 = year;
  var month2 = parseInt(month) - 1;
  if (month2 == 0) {
    year2 = parseInt(year2) - 1;
    month2 = 12;
  }
  var day2 = day;
  var days2 = new Date(year2, month2, 0);
  days2 = days2.getDate();
  if (day2 > days2) {
    day2 = days2;
  }
  if (month2 < 10) {
    month2 = '0' + month2;
  }
  var t2 = year2 + '-' + month2 + '-' + day2;
  return t2;
}

HTML 锚点跳转平滑动画

    $('a[href*=#],area[href*=#]').click(function() {
        if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
            var $target = $(this.hash);
            $target = $target.length && $target || $('[name=' + this.hash.slice(1) + ']');
            if ($target.length) {
                var targetOffset = $target.offset().top;
                $('html,body').animate({
                        scrollTop: targetOffset
                    },
                    200);
                return false;
            }
        }
    });

yum 安装 MongoDB 3.6

安装步骤

CentOS7 直接 yum 安装 会出现 No package mongodb-org available.

首先,编辑 MongoDB 安装源

vim /etc/yum.repos.d/mongo.repo

然后粘贴如下内容并保存退出

[mongodb-org-3.6]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/3.6/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-3.6.asc

清理缓存

yum clear all

然后进行安装

yum -y install mongodb-org

配置文件位置

vim /etc/mongod.conf 

修改 bindIp: 0.0.0.0 可以外部访问

重启 mongod 服务

systemctl restart mongod.service 

客户端

客户端可使用 NoSQL Manager for MongoDB Freeware,下载地址:

https://www.mongodbmanager.com/download

如无法连接检查防火墙是否放行 27017 端口

参考文献

Centos 下安装配置 Mongodb3.6

https://www.cnblogs.com/hackyo/p/7967170.html

Window 下安装直接下载安装包

Windows 平台安装 MongoDB

http://www.runoob.com/mongodb/mongodb-window-install.html

Windows 启动 mongodb

mongod.exe --dbpath c:\home\db

CentOS 7 安装 Python3 与 Python2共存

CentOS 7 已经默认安装 Python 2.7.5 , 使用 Python -V 可查看当前版本,使用 which python 查看当前 Python 文件的可执行文件位置

编译前先安装常用相关包

yum install zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gcc make

然后下载安装包编译

cd ~
wget https://www.python.org/ftp/python/3.6.2/Python-3.6.2.tar.xz
tar -xvJf  Python-3.6.2.tar.xz
cd Python-3.6.2
./configure prefix=/usr/local/python3
make && make install

安装完成后 Python3 就在 /usr/local/python3 目录下了

我们可以将 python3 的命令软件链接到 该目录下

ln -s /usr/local/python3/bin/python3 /usr/bin/python3
Continue reading CentOS 7 安装 Python3 与 Python2共存

fSelect.js select 下拉多选框 checkbox 的使用方法

<!DOCTYPE html>
<html>
<head>
	<link href="jquery.fSelect.css" rel="stylesheet" type="text/css" />
	<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
	<script src="jquery.fSelect.js"></script>
	<script>
		$(function() {
			$('.demo').fSelect();
		});
	</script>
</head>
<select class="demo" multiple="multiple">  
    <optgroup label="Languages">  
        <option value="cp">C++</option>  
        <option value="cs">C#</option>  
        <option value="oc">Object C</option>  
        <option value="c">C</option>  
    </optgroup>  
    <optgroup label="Scripts">  
        <option value="js">JavaScript</option>  
        <option value="php">PHP</option>  
        <option value="asp">ASP</option>  
        <option value="jsp">JSP</option>  
    </optgroup>  
</select>
</html>

简单测试一下 PHP mt_rand( ) 函数一秒钟重复值

<?php
echo "<pre>";

$start = microtime(true);
$end = microtime(true);
$rand = [];
$i = 0;
do{
    $theRand = mt_rand(0,99999);
    if(in_array($theRand,$rand)){
        $i=$i+1;
    }
    $rand[] = $theRand;
    $end = microtime(true);
}while(($end-$start)<1);

echo $i;
echo "<br>";
echo count($rand);
?>

多次测试后,

当随机数为 0 – 99999 时,每秒约能生成 25000 个随机数,重复的约为 3000

当随机数为 0 – 999999 时,每秒约能生成 25000 个随机数,重复的约为 300

机数为 0 – 9999999 时,每秒约能生成 25000 个随机数,重复的约为 30

一秒钟内生成两个随机数撞车的概率还是蛮大的

起因是做活动,订单号貌似重复了,高峰期一分钟八单

一些 PHP 函数

两个日期之间的全部日期

//两个日期之间的日期数组形式
function prDates($start,$end){
  $dt_start = strtotime($start);
  $dt_end = strtotime($end);
  $date = array();
  while ($dt_start<=$dt_end){
    $date[] = date('Y-m-d',$dt_start);
    $dt_start = strtotime('+1 day',$dt_start);
  }
  return $date;
}

位数补零

$number=sprintf ( "%02d",$number);

数组的指定key后面插入数据

function array_push_after_key($array, $data=null, $key=false){
  $data  = (array)$data;
  $offset  = ($key===false)?false:array_search($key, array_keys($array));
  $offset  = ($offset)?$offset:false;
  if($offset){
    return array_merge(
      array_slice($array, 0, $offset+1),
      $data,
      array_slice($array, $offset+1)
    );
  }else{  //找不到key,就直接加到末尾
    return array_merge($array, $data);
  }
}

PHP 正则匹配替换 HTML 的 IMG 标签 SRC 属性,添加图片域名

private function preg_match($img){
  $newImg = preg_replace('/(<img.+?src=")(.*?)/','$1'.base_url().'$2', $img);
  return $newImg;
}

PHP 图片压缩至指定尺寸 封装函数

/**
 * @param $img 图片地址
 * @param string $width 宽
 * @param string $height 高
 * @param string $ratio 保持原比例
 * @return string 生成的地址
 */
public function resize_fuc($img, $width, $height, $ratio)
{

	$info = get_img_info($img);
	$name = pathinfo($img)['filename'];
	$dirname = pathinfo($img)['dirname'];
	$ext = pathinfo($img)['extension'];

	$im = NULL;
	$type = strtolower($info['type']);

	if (!in_array($type, ['jpg', 'jpeg', 'gif', 'png'])) {
		return FALSE;
	}
	$type = ($type == 'jpg' ? 'jpeg' : $type);

	$scale = $info['width'] / $info['height'];

	if ($ratio == TRUE) {
		$forScale = $width / $height;
		$x = 0;
		$y = 0;
		if ($scale >= $forScale) {
			$width = (int)($height * $scale);
			$rate = $info['height']/$height;
		} else {
			$height = (int)($width / $scale);
			$rate = $info['width']/$width;
		}
	} else {
		$forScale = $width / $height;
		if ($scale >= $forScale) {
			$x = ($info['width'] - $info['height'] * $forScale) / 2;
			$y = 0;
			$rate = $info['height'] / $height;
		} else {
			$x = 0;
			$y = ($info['height'] - $info['width'] / $forScale) / 2;
			$rate = $info['width'] / $width;
		}
	}

	if($width>$info['width'] || $height>$info['height']){
		return;
	}


	$imageCreateFun = 'imagecreatefrom' . $type;
	$im = $imageCreateFun($img);
	$thumb = $dirname . '/' . $name . '_tmp' . "." . $ext;

	$imageFun = 'image' . $type;
	$imageFun($im, $thumb);

	$thumbNew = imagecreatetruecolor($width, $height);

	imagecopyresampled(
		$thumbNew, $im,
		0, 0, intval($x), intval($y),
		intval($width * 1), intval($height * 1), intval($width * $rate), intval($height * $rate)
	);

	$imageFun($thumbNew, $thumb);

	imagedestroy($im);
	imagedestroy($thumbNew);

	rename($thumb,$img);
	return $img;
}
function get_img_info($img) {
    if(!is_file($img) || !in_array(strtolower(pathinfo($img)['extension']),['jpg','jpeg','bmp','gif','png'])){
        return false;
    }
    $img_info = getimagesize($img);
    if ($img_info !== false) {
        $img_type = strtolower(substr(image_type_to_extension($img_info[2]), 1));
        $info = array("width" => $img_info[0], "height" => $img_info[1], "type" => $img_type, "mime" => $img_info['mime'], );
        return $info;
    } else {
        return false;
    }
}