Tag Archives: front end

Gulp failed to run

$ gulp
[18:09:47] Failed to load external module @babel/register
[18:09:47] Requiring external module babel-register
C:\users\astros\file\es6pro\node_modules\[email protected]@babel-core\lib\transformation\file\opti        ons\build-config-chain.js:154
      throw err;
      ^

SyntaxError: C:\users\astros\file\es6pro\.babelrc: Error while parsing JSON - Unexpected EOF at lin        e 1 column 2 of the JSON5 data. Still to read: ""
    at error (C:\users\astros\file\es6pro\node_modules\[email protected]@json5\lib\json5.js:56:25)
    at word (C:\users\astros\file\es6pro\node_modules\[email protected]@json5\lib\json5.js:393:13)
    at value (C:\users\astros\file\es6pro\node_modules\[email protected]@json5\lib\json5.js:493:56)
    at Object.parse (C:\users\astros\file\es6pro\node_modules\[email protected]@json5\lib\json5.js:508:1        8)
    at ConfigChainBuilder.addConfig (C:\users\astros\file\es6pro\node_modules\[email protected]@ba        bel-core\lib\transformation\file\options\build-config-chain.js:150:65)
    at ConfigChainBuilder.findConfigs (C:\users\astros\file\es6pro\node_modules\[email protected]@        babel-core\lib\transformation\file\options\build-config-chain.js:96:16)
    at buildConfigChain (C:\users\astros\file\es6pro\node_modules\[email protected]@babel-core\lib        \transformation\file\options\build-config-chain.js:61:13)
    at OptionManager.init (C:\users\astros\file\es6pro\node_modules\[email protected]@babel-core\l        ib\transformation\file\options\option-manager.js:354:58)
    at compile (C:\users\astros\file\es6pro\node_modules\[email protected]@babel-register\lib\        node.js:103:45)
    at loader (C:\users\astros\file\es6pro\node_modules\[email protected]@babel-register\lib\n        ode.js:144:14)

The reason why

occurs above is because babelrc is empty

, in babelirc.js, write

//presets转成2015
//写法需安装cnpm install babel-preset-es2015 --save-dev
{
  "presets":["es2015"]
}

ok

How to restrict input field to only input pure numbers in HTML

limit input input box can only enter pure Numbers

1, the onkeyup = "value, value = replace (/ [^ \] d/g,") "

USES the onkeyup event, and has the bug, that is, in the state of Chinese input method, after Chinese characters are input, enter directly, the letter

will be input directly

2, onchange = "value, value = replace (/ [^ \] d/g,") "

USES the onchange event. After input content, only the input loses focus will get the result, and the response

cannot be made when input

3, the oninput = "value, value = replace (/ [^ \] d/g,") "

USES the oninput event, which perfectly solves the above two problems. There are no other problems in the test for the time being.

code example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>input</title>
</head>
<body>
    只能输入纯数字的输入框:<input type="text" name="" oninput="value=value.replace(/[^\d]/g,'')">
</body>
</html>

above code has been tested in Google, firefox, baidu, UC, IE11, 360 fast, QQ, Edge browser, please feel free to use,

thanks for qq_38726717, xiao xiao xin feedback in the comments section.

Exploring the streaming call of underscore

introduction
The

underscore is a JavaScript tool library that provides a full range of functional programming capabilities. It contains many utility functions such as each, Map, Reduce,filter, and so on. While es5,es6 already includes most of these, looking at the source code to see the underlying implementation of these functions will help you gain a deeper understanding of native js
The

underscore is defined as pure functions and supports chained calls to a one-way data source. In the chain of functions, data flows magically from one function to another as if passing through a pipe.

  const result = _([1, 2, 3, 4, 5, 6, 7]).chain().map((item) => {return item * 2;}).filter((item) => {
        return item > 10;
        }).value();

operation process is as follows:

  • takes the array as the starting data source, runs _([1, 2, 3, 4, 5, 6, 7]) to generate instance objects, and then calls the method chain on the instance to enable it to chain call.
  • runs the map function and multiplies each element of the array by 2 to form a new array. 14], filter out the value of less than 10
  • value () method to obtain the final run results [12, 14]

    the above process shows that the data source enters from the initial port and is passed back layer by layer. Each function will receive the result processed by the previous function and send the result run by itself to the next function. The data flows back like a stream of water as it enters a pipe, forming a streaming call. Next, implement its overall operation mechanism.

    source implementation

    create constructor

    defines the constructor _, if obj is a piece of ordinary data, when running _(obj), this points to window, the result returns the instance object new _(obj), then the object contains the property wrapped, the corresponding value is obj.

    (function (global) {
    
      function _(obj) {
        if (obj instanceof _) {
          return obj;
        }
        if (!(this instanceof _)) {
          return new _(obj);
        }
        this.wrapped = obj;
      }
    
      _.prototype.value = function () {
        return this.wrapped;
      };
    
      global._ = _;
      
    })(window);
    
    

    implements streaming calls

    defines an object allExports, assigns the defined utility functions to the properties of the object, and passes in the mixin function to run

    function chain(obj) {
        const _instance = _(obj);
        _instance._chain = true;
        return _instance;
      }
    
      function map(obj, iteratee) {...}
    
      function filter(obj, iteratee) {...}
    
      const allExports = {
        chain,
        map,
        filter,
      };
    
      mixin(allExports);
    

    runs the mixin function, and the parameter obj is the allExports defined above. Key is the name of the function,func corresponds to the specific function.

    func is not bound directly to the constructor, but to the constructor’s prototype object. As can be seen from here,_(data).chain().map().filter() calls chain,map,filter () during the execution process, it actually calls the function

    defined in the mixin mounted on the prototype object

    is executed as follows :

    • assumption data = [1, 2, 3], _ (data) is the result of instance object {wrapped: [1, 2, 3]}
    • call instance object chain method, below the running function. The result = [[1, 2, 3]].
    • func points to the chain function and adds _chain attribute to the instance object.
    • chainResult function determines that the current instance object branch does not support chain calls. If it supports subsequent newly generated instance objects, _chain is added as true. Return the new instance object
    • the data of the new instance object is still {wrapped:[1,2,3]}. Func points to the map function. Map function returns result [2,4,6]. ChainResult finds support for chain call run _([2,4,6]) to generate a new instance object
    • . At this point, this.wrapped has become [2,4,6]. It can be seen from here that every time a function is run, it will generate new instance object by taking the data processed by the function as parameter, and return this new instance object to continue calling other functions, and generate new instance object again. The new instance object continues to call with the processed data, forming the data flow.
    function mixin(obj) {
        const array = Object.keys(obj);
        array.forEach((key) => {
          const func = obj[key];
          _.prototype[key] = function () {
            const result = [this.wrapped];
            Array.prototype.push.apply(result, arguments);
            return chainResult(this, func.apply(_, result));
          };
        });
      }
    
      function chainResult(_instance, obj) {
        return _instance._chain ?_(obj).chain() : obj;
      }
    

    complete code

    (function (global) {
      function _(obj) {
        if (obj instanceof _) {
          return obj;
        }
        if (!(this instanceof _)) {
          return new _(obj);
        }
        this.wrapped = obj;
      }
    
      _.prototype.value = function () {
        return this.wrapped;
      };
    
      function chain(obj) {
        const _instance = _(obj);
        _instance._chain = true;
        return _instance;
      }
      
      //map函数的简单实现,支持数组和对象
      function map(obj, iteratee) {
        const keys = !Array.isArray(obj) && Object.keys(obj);
        const len = keys ?keys.length : obj.length;
        const result = [];
        for (let i = 0; i < len; i++) {
          const current_key = keys ?keys[i] : i;
          result.push(iteratee(obj[current_key]));
        }
        return result;
      }
    
      //filter函数的简单实现,,支持数组和对象
      function filter(obj, iteratee) {
        const keys = !Array.isArray(obj) && Object.keys(obj);
        const len = keys ?keys.length : obj.length;
        const result = [];
        for (let i = 0; i < len; i++) {
          const current_key = keys ?keys[i] : i;
          if (iteratee(obj[current_key])) {
            result.push(obj[current_key]);
          }
        }
        return result;
      }
    
      function mixin(obj) {
        const array = Object.keys(obj);
        array.forEach((key) => {
          const func = obj[key];
          _.prototype[key] = function () {
            const result = [this.wrapped];
            Array.prototype.push.apply(result, arguments);
            return chainResult(this, func.apply(_, result));
          };
        });
      }
    
      function chainResult(_instance, obj) {
        return _instance._chain ?_(obj).chain() : obj;
      }
    
      const allExports = {
        chain,
        map,
        filter,
      };
    
      mixin(allExports);
    
      global._ = _;
    })(window);
    
    

JS prompt cannot read property ‘style’ of undefined

"order": [[6, "asc"]],

Instead of

"order": [[0, "asc"]],

reason, only 3 columns, I chose column 6 to sort…

so there’s a sense that it’s out of bounds, so the error is

<div class="box-body">
    <table class="table table-bordered table-striped" id="mytable" role="grid" aria-describedby="user" style="width: 100%;">
        <thead>
        <tr>
            <th>名字</th>
            <th>年龄</th>
            <th>性别</th>
        </tr>
        </thead>
    </table>
</div>

<script>
    var table;

    $(function () {
        table = $('#mytable').DataTable({
            "sScrollY": $(this).height() -280,
            "serverSide": true,
            "processing": true,
            "paging": true,
            "lengthChange": false,
            "searching": false,
            "ordering": false,
            "info": true,
            "autoWidth": true,
            "order": [[0, "asc"]],//按照第几列排序
            "pageLength": 10,
            "bLengthChange": true,
            "oLanguage": lang,
            "ajax": {
                "url": "${CONTEXT_PATH}/admin/essay/voteList",
                "type": "POST",
                "dataSrc": "data",
                "data": function (d) {
                    d.extra_search = $("#form").serialize();
                }
            }, 
            "aoColumnDefs": [ { "bSortable": false, "aTargets": [ 5 ] }],
            "columns": [
                {"data": "name"},
                {"data": "age"},
                {"data": "sex"}
            ]
        });
    });


</script>


CSS: several ways to center the box vertically and horizontally

method 1: width and height known.

idea:
relative positioning of the parent element
absolute positioning of the child element
left: 50%; top: 50%;
margin-left: negative half width.
margin-top: minus half of the height;

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>居中</title>
    <style type="text/css">
        #box{
            width: 400px;
            height: 200px;
            position: relative;
            background: red;
        }
        #box1{
            width: 200px;
            height: 100px;
            position: absolute;
            top: 50%;
            left: 50%;
            margin-left: -100px;
            margin-top: -50px;
            background: green;
        }
    </style>
</head>
<body>
    <div id="box">
        <div id="box1">

        </div>
    </div>
</body>
</html>

method 2: width and height themselves unknown

means that the subbox itself still has a width and a height that it doesn’t know.
relative positioning of parent box
absolute positioning of child box
top, right, bottom, left all 0
margin: auto;

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>居中</title>
    <style type="text/css">
        #box{
            width: 800px;
            height: 400px;
            position: relative;
            background: red;
        }
        #box1{
            width: 100px;
            height: 50px;
            position: absolute;
            top: 0;
            right: 0;
            bottom: 0;
            left: 0;
            margin: auto;
            background: green;
        }
    </style>
</head>
<body>
    <div id="box">
        <div id="box1">

        </div>
    </div>
    <script type="text/javascript">

    </script>
</body>
</html>

method 3: flex layout

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>垂直居中</title>
    <style type="text/css">
        .box{
            width: 400px;
            height: 200px;
            background: #f99;
        }
        .box1{
            width: 200px;
            height: 100px;
            background: green;
        }
        .center{
            display: flex;
            justify-content: center;//实现水平居中
            align-items: center;//实现垂直居中
        }
    </style>
</head>
<body>
    <div class="box center">
        <div class="box1">

        </div>
    </div>
</body>
</html>

Method 4: translation positioning +transform

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>css3让一个盒子居中</title>
    <style type="text/css">
        .parent_box{
            width: 400px;
            height: 200px;
            background: red;
            position: relative;
        }
        .child_box{
            width: 200px;
            height: 100px;
            background: #9ff;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate( -50%,-50%);
        }
    </style>
</head>
<body>
    <div class="parent_box">
        <div class="child_box">

        </div>
    </div>
</body>
</html>

method 5: table-cell layout

parent display: table-cell; vertical-align: middle; Sub-level margin: 0 auto;

** horizontal center

plus a horizontal center: margin-left: 50%; transform: translateX(-50%);

Connection between PHP 7.4 and MySQL (MariaDB) under Ubuntu (kali Linux)

PHP7 or above has abolished the mysql function library, so the mysql_connect() function is no longer available. The new function libraries MySQli and PDO can completely replace this library. This article mainly introduces two kinds of library functions, PHP and mysql connection and encountered problems.

experiment, all content in ubuntu18.04.3 can also be fully run.

installation problem

PHP is connected to mysql using apache+PHP+mysql, as each part has been pre-installed in kali, see resources for details: kali installs apache, mysql, PHP. Here I want to talk about the installation need to pay attention to the problem, apache and mysql installation generally will not have problems, focus on PHP installation. After the configuration of resources is completed, create a new file index.php under /var/www. HTML folder. The content is as follows:

<?php

phpinfo();

?>

opens apache, which is enabled by default. If you are not sure, you can run the following command:

/etc/init.d/apache2 start

the following results:

the server has opened, the browser input address: http://localhost/index.php, appeared normal PHP configuration information:
page provides PHP configuration details and extension module has been installed, need to emphasize the extension module!!!!!! This can cause a very common problem: the PHP information page displays normally, the static PHP page can be displayed, but the dynamic interactive page is blank! , which is often the result of PHP’s corresponding extension module not being installed. For example, the modules needed this time are MySQli and PDO (these two libraries are independent, but the two libraries are used to realize the connection between PHP and mysql respectively). However, in the latest VERSION of PHP, mySQli library will not be installed by default, which causes the mysqli functions in the PHP page will not be executed, forming a blank page.


direct command line input:

php -m

lists the extensions that have been installed:

I have now installed them. If you do not have these modules, you can install them with the following command (see reference 2 for more details) :

sudo apt-get install php7.4-mysqli //这里我的php版本是7.4.9
sudo apt-get install php7.4-PDO

at this point, all configuration is complete.

MySQL create user with authorization

Mysql can log in confidentially under

kali and default to root, while ubuntu requires a more detailed command:

mysql  #kali下
--------------------------------
mysql -u root -p #kali下和ubuntu下均可,更正式

kali>

or ubuntu kali is recommended

one of the most common problems here is to report an error:
ERROR 2002 (HY000) : Can ‘t connect to local MySQL server through socket’/var/run/mysqld/mysqld. The sock ‘
there are all kinds of solution to the problem, sometimes only restart MySQL Can solve the problem:

systemctl restart mysql

create user

database operation commands are case sensitive.
into Mysql, the relevant user creation and authorization commands are as follows:

#drop database kali; #由于已经完成数据库的操作,数据库已经存在,这里将其删除,重新演示
show databases; #列出当前存在的数据库
create database kali;  #创建数据库kali
use kail;  #使用kali
#drop user 'lee'@'localhost';  #删除当前用户lee
create user 'lee'@'localhost' identified by '123';  #创建新用户,这条命令涉及PHP代码,下面详细说
select user,host,password from mysql.user; #列出所有用户、所属主机、密码(默认经过加密)


identified by ‘123’; **create user ‘lee’ @’ localhost ‘identified by’ 123 ‘;
create user ‘username’ @’ host ‘identified by’ password ‘;
username: created username;
host: specify which host the user can log in on. If it is a local user, use localhost. If you want the user to log in from any remote host, use the wildcard %;
password: the user’s login password, the password can be empty, if empty, the user can log in the server without the password;

The user information created by

is placed in mysql.user.

user authorization

authorizes the new user created. Authorization refers to the operation that the user can perform on the database, such as adding, deleting, modifying, checking, etc. The command is:

grant all privileges on kali.* to 'lee'@'localhost' identified by '123' with grant option;
flush privileges;  #权限刷新

grant privileges on databasename. Tablename to ‘username’ @’ host ‘

privileges: privileges on the user, such as SELECT, INSERT, UPDATE, etc. ALL
databasename: databasename
tablename: Table name, represented by * if you want to grant the user permission to operate on all databases and tables.

for more detailed permissions, see resources 3: MySQL create users and authorizations. As a matter of fact, the connection between PHP and mysql can already be detected at this point. For a clearer representation, the contents of the database can be printed on the page. First create the content.

database content creation

basic database operation, command as follows:

show tables;  #显示当前数据库下所有列表
create table users(
    -> id int(10),
    -> username varchar(7) );  #创建table,赋予属性
describe users;  #描述表
insert into users value (1,'paradox');  #插入数据
select * from users;  #显示数据

PHP7 connection mysql

PHP7 has abolished the mysql library. If you want to establish PHP and mysql interaction, you can do it through mysqli and PDO library functions. This article does not elaborate on the differences and USES of mysql, MySQli and PDO. You can read Resources 4-6 for details.

PHP mysqli interacts with mysql

mysqli is object-oriented and process-oriented. Set up mysqli.php in the folder /var/www. HTML /. The content is as follows:

<?php
    /*
    面向对象风格,格式及参数说明:
    $mysqli = new Mysqli($serve,$username,$password,$dbname);
    $serve:所使用的用户主机名称,这里是本地用户localhost
    $username: 数据库用户名,上面设置为lee
    $password:用户对应的密码
    $dbname:所使用的数据库。默认的话,会调用上一个打开的数据库
    */
    $mysqli = new mysqli("localhost", "lee", "123", "kali");
    if(!$mysqli)  {
        echo"database error";
    }else{
        echo"php env successful";
    }
    $mysqli->close();
?>

your browser input address: http://localhost/mysqli.php, the connection is successful.

PHP PDO interacts with mysql

PDOPDO’s biggest advantage over MySQLi is that PDO supports a wide variety of databases, while MySQLi only supports MySQLi. PDO’s advantages will come into play when a program wants to switch from mysql to SQL Server or Oracle in the future, because the database switch is transparent to the interface, the PHP code changes very little, and if you’re using MySQLi, you’ll have to rewrite everything you use for the database.
PDO can establish a connection in three ways: connects to the database in the form of parameters; Connect to the database through A URI; Connect to the database in the form of a configuration file. The latter two require configuration files, the first of which is used here. Similarly, under /var/www. HTML/create a file called pdo.php that reads as follows:

<?php
$dbms='mysql';
$dbName='kali';
$user='lee';
$pwd='123';
$host='localhost';
$dsn="$dbms:host=$host;dbname=$dbName";
$pdo=new PDO($dsn,$user,$pwd);
echo "PDO连接MySQL成功";
?>

, the parameter here has the same meaning, just pay attention to the format of $DSN. Enter the address http://localhost/pdo.php in the browser and the connection is successful as follows:

Of course,

can also output the contents of the database, create a file pdoo.php, the content is as follows:

<?php
header("Content-type:text/html;charset=utf-8");
$dns = 'mysql:host=localhost;dbname=kali';
$username = 'lee';
$password = '123';

try{ // PDO连接数据库若错误则会抛出一个PDOException异常
	$PDO = new PDO($dns,$username,$password);
	$result = $PDO->query('select * from users');
	$data = $result->fetchAll(PDO::FETCH_ASSOC); 
	// PDO::FETCH_ASSOC表示将对应结果集中的每一行作为一个由列名索引的数组返回
	print_r($data);
} catch (PDOException $error){
	echo 'connect failed:'.$error->getMessage();
}

?>

your browser input: http://localhost/pdoo.php, shows the database content:

this is the front insert data in the database:

ERROR in static/js/app.xxxxxxx.js from UglifyJs Unexpected token: operator (>)

:
vue family barrel USES the vue-qrcode-directive component to generate the two-dimensional code in the project. There is no error in using NPM run dev in the development process. To NPM run build packaging ERROR, such as the ERROR in the static/js/app f1ecb9a5673e78cc442b. Js from UglifyJs Unexpected token: operator (& gt;) [./~/_vue – [email protected] @ vue – qrcode – directive/index, js: 4, 0] [static/js/app. F1ecb9a5673e78cc442b. Js: 17412]

analysis reason :
weback default webpack. Optimize. UglifyJsPlugin cannot compress es6 code files. Along the way, we can simply convert es6 code to ES5 using Babel.
the reason must still be on webpack.config.js. After repeated observations. The problem occurred in the loader configuration, where an item was configured for js file transformation.

solution : (the same problem occurs in _quill-image-drop-module, _vue-qrcode-directive)

module: {
  rules: [
    {
        test: /\.js$/,
        loader: "babel-loader",
        include: [
          resolve("src"),
          resolve("test"),
          resolve(
            "node_modules/[email protected]@quill-image-drop-module"
          ),
          resolve(
            "node_modules/[email protected]@vue-qrcode-directive"
          )
        ],
      }
  ]
}