博文

PHP8 —— New String Helpers

新增了三个字符串函数,str_starts_with, str_ends_with, str_contains, PHP 的函数这么方便,很难想象竟然一直没有这几个。 str_starts_with 判断字符串是否以另一个字符串开头,在PHP7以及之前 $id = 'inv_abcdefgh'; $result = strpos($id, 'inv_') === 0; var_dump($result); // true PHP8 中可以直接这么写 $result = str_starts_with($id, 'inv_'); str_ends_with 判断字符串是否以另外一个字符串结尾,在 PHP7 及之前,比较麻烦,通常是这么写 $id = 'abcd_inv'; $result = strpos(strrev($id), strrev('_inv')) === 0; 或者 $result = substr($id, -1 * strlen('_inv')) === '_inv'; 或者上正则吧 $result = preg_match('/_inv$/', $id) === 1; 看起来都是比较麻烦的。PHP8 里面可以简化成下面这样了 $id = 'abcd_inv'; $result = str_ends_with($id, '_ind'); str_contains 字符串包含,PHP8 之前一般就是 strpos 来实现了 $url = 'https://example?for=bar'; $result = strpos($url, '?') !== FALSE; PHP8 就直接一点 $result = str_contains($url, '?');

JavaScript 数据类型

类型 JavaScript 语言的每个值都属于一种数据类型。JavaScript 语言规定了7中类型: Undefined Null Boolean String Number Symbol (ES6开始加入) Object Undefined, Null Undefined 表示未定义,有一个值 undefined。任何变量在赋值是 Undefined 类型,值为 undefined。一般我们可以用全局变量 undefined 表示这个值,或者 void 运算符将任意表达式变成 undefined。undefined 是一个变量而非关键字,为了避免被无意中篡改,建议使用 void 0 来获取 undefined 值。 Null 表示“定义了但为空”,与 Undefined 有一定的表义差别。Null类型只有一个值 null,它是语言关键字,在任何代码中都可以使用 null 来获得 null 值。 实际代码中,不要将变量赋值为 undefined,这样可保证所有值为 undefined 的变量,都是从来未赋值状态。 Boolean Boolean 类型有两个值,true 和 false,表示真和假,均为语言关键字。 String String 表示文本数据,最大长度为 2 53 - 1。 String 的意义并非“字符串”,而是字符串的 UTF-16 编码,字符串的最大长度,受编码长度影响。 JavaScript 字符串是不可变量,构造之后没有任何方法变更内容,具有值类型的特征。 JavaScript 将每个 UTF-16 单元作为一个字符,处理非 BMP(超出 U+000 ~ U+FFF范围)字符是,需要格外小心。 Number Number 类型有 18437736874454810627(即 2 64 - 2 53 +3)个值,基本符合 IEEE 754-2008 规定的双精度浮点数规则,除了一下例外: NaN,占用 9007199254740990,这是原来符合 IEEE 规则的数字 Infinity,无穷大 -Infinity,负无穷大 JavaScript中,+0 和 -0 在加法中无差别,在除法中有差别。1/+0 、1/-0 分别得到 Infinity 和 -Infinity。 ...

Java memory model and happens-before rules

Why define the Java memory model? Most modern computer architectures use a symmetric multiprocessor architecture. Each processor has an independent register set and cache, and multiple processors can execute different threads in the same process at the same time. This is called processor out-of-order execution. In Java, different threads may access the same shared or shared variable. If the compiler or processor is allowed to optimize these accesses, it is likely that an unthinkable problem will occur, which is referred to as compiler reordering. In addition to out-of-order execution of processors, reordering of compilers, and reordering of memory systems. Therefore, the Java language specification introduces the Java memory model, which restricts the compiler and processor by defining multiple rules, mainly for visibility and order. Three basic principles: atomicity, visibility, and orderliness. The Java memory model involves several keywords: locks, volatile fields, final modifi...

Java 学习笔记 —— 创建Stream

可以使用如下方法创建Stream: 1)在Stream界面中使用静态工厂方法, 2)Iterable或Arrays上的流方法。 在Stream 接口中使用静态工厂方法 Java 8中新的 java.util.stream.Stream 接口提供了几种用于创建流的静态方法。 具体来说,我们可以使用静态方法 Stream.of , Stream.iterate 和 Stream.generate 。 static <T> Stream<T> of(T... values) 标准库中of方法的实现实际上委托给Arrays类中的stream方法 @SafeVarargs public static<T> Stream<T> of(T... values) { return Arrays.stream(values); } 例子: String days = Stream.of("monday", "tuesday", "wednesday") .collect(Collectors.joining(",")); System.out.println(days); // prints monday,tuesday,wednesday static <T> Stream<T> iterate(T seed, UnaryOperator<T> f) 根据Javadocs,此方法“返回通过将函数f迭代应用到初始元素种子而生成的无限、有序的Stream”。 List<BigDecimal> nums = Stream.iterate(BigDecimal.ONE, n -> n.add(BigDecimal.ONE) ) .limit(10) .collect(Collectors.toList()); System.out.println(nums); // prints [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Stream.iterate(LocalDate.now(), ld -> ...

PDO vs MySQLi

PDO MySQLi Database support 12 different drivers MySQL only API OOP OOP + procedural Connection Easy Easy Named parameters Yes No Object mapping Yes Yes Prepared statements  (client side) Yes No Performance Fast Fast Stored procedures Yes Yes Collection // PDO $pdo = new PDO("mysql:host=localhost;dbname=database", 'username', 'password'); // mysqli, procedural way $mysqli = mysqli_connect('localhost','username','password','database'); // mysqli, object oriented way $mysqli = new mysqli('localhost','username','password','database'); Named parameters PDO $params = array(':username' => 'test', ':email' => $mail, ':last_login' => time() - 3600); $pdo->prepare(' SELECT * FROM users WHERE username = :username AND email = :email AND last_login > :last_login'); ...

Fold function in haskell

let’s first take a look at some list functions, and see what’s the characteristic they all share sum : computes the sum of the numbers of a structure; and : returns the conjunction of a container of Bools; map : map f xs is the list obtained by applying f to each element of xs . There three are all common list function, and act very differently, but can be defined recursively using pattern matching as follow: mySum :: ( Num t) => [t] -> t mySum [] = 0 -- sum of empty is 0 mySum (x : xs) = x + mySum xs -- otherwise, add first element to sum of rest of the list myAnd :: [ Bool ] -> Bool myAnd [] = True -- and of empty is True myAnd (x : xs) = x && myAnd xs -- otherwise, return the conjunction of first element and the rest of list myMap :: (t -> t) -> [t] -> [t] myMap _ [] = [] -- map any function to empty is empty myMap f (x : xs) = f x : myMap f xs -- otherwise, prepend...

Turtle Geometry Tutorial 1

图片
We have a little turtle who holds a pen, on our display screen. The turtle can respond to some commands: FORWARD , BACK , RIGHT and LEFT . * FORWARD 100 : The turtle will move 100 step on the screen, in the direction it is facing. * RIGHT 100 : The turtle will turn its head 90° clockwise in place. Repeating the commands above 4 times will get us a square with side 100 units long. forward 100 right 90 forward 100 right 90 forward 100 right 90 forward 100 right 90 We can rewrite the commands use repeat loop, as repeat 4 [ forward 100 right 90 ] This will give us the same square as before. At the next step we’ll teach our little turtle some new command, here we add square to the its vocabulary. to square repeat 4 [forward 100 right 90 ] end then we can use this new square command to draw the same square. Here comes some thing interesting: repeat 4 [ square right 90 ] repeat 12 [ square right 30 ] OK, that is all for today. Happy ...

D3js Data-binding basics

图片
We can use d3.select() to select and change DOM elements, and we can create and remove elements based on data. const books = [ 'Eloquent JavaScript' , 'JavaScript: The Good Parts' , 'JavaScript: The Definitive Guide' , 'You Don’t Know JS' ] d3.select( 'body' ).selectAll( 'div.books' ) .data(books) .enter() .append( 'div' ) .attr( 'class' , 'books' ) .html( function (d) { return d }) The result is: d3.selectAll() We start a selection using d3.selectAll() with a CSS identifier. Often there’s no elements match this identifier, and we then use .enter() function to create new elements. .data() We associate the data array with the elements which we selected using d3.selectAll() . For example we can access the first item of the array using code like this: document.getElementsByClassName( "books" )[ 0 ].__data__ .enter() and .exit() When we have more data items t...

Global functions and vars in Vue components system

There are several ways in Vue to manage global var and function in the component system: 1. Put all functions and vars in a js file like ‘helper.js’, and import this file in components where we need these functions and vars. It’s a very clear way because we can see directly where the functions and vars are from. 2. Add the function or var to Vue.prototype , like Vue.prototype.$myfunciotn = ... , and then we can use it in component by calling this.$myfunction() 3. Of course we can use Vue Plugins to inject these functions and vars. The official document is here . MyPlugin.install = function (Vue, options) { // 1. add global method or property Vue.myGlobalMethod = function () { // something logic ... } // 2. add a global asset Vue.directive( 'my-directive' , { bind (el, binding, vnode, oldVnode) { // something logic ... } ... }) // 3. inject some component options Vue.mixin({ created: function () { // someth...

Lambda structure

Function $$\lambda x.x$$ is a simple function. It has a head, which is a lambda ($\lambda$) followed by a variable name, and a body, and the head and body of the function is separated by a dot ($.$). When we applied this function to an argument, the x in the body will have the value of that given argument. Alpha equivalence $$\lambda x.x$$ $$\lambda y.y$$ $$\lambda z.z$$ all there three are the same thing. The letters here are not meaningful, just a way of expression. This equivalence is called alpha equivalence. Beta reduction Beta reduction is the process in which we apply a function to arguments, substitute the input expression for all bound variables in the body, and eliminate the head. If we apply $\lambda x.x$ to a number, for example 42, we can substitute 42 for each $x$ in the body, and eliminate the head: $$(\lambda x.x) 42$$ $$42$$ Another example: apply function $(\lambda x.x*4)$ to 8, we got $$(\lambda x.x*4) 8$$ $$8*4$$ $$32$$ We can apply function to another funct...