## codesignal practice 4

### 10

``````You are given an array of non-negative integers numbers. You are allowed to choose any number from this array and swap any two digits in it. If after the swap operation the number contains leading zeros, they can be omitted and not considered (eg: 010 will be considered just 10).

Your task is to check whether it is possible to apply the swap operation at most once, so that the elements of the resulting array are strictly increasing.

Example

For numbers = [1, 5, 10, 20], the output should be makeIncreasing(numbers) = true.

The initial array is already strictly increasing, so no actions are required.

For numbers = [1, 3, 900, 10], the output should be makeIncreasing(numbers) = true.

By choosing numbers = 900 and swapping its first and third digits, the resulting number 009 is considered to be just 9. So the updated array will look like [1, 3, 9, 10], which is strictly increasing.

For numbers = [13, 31, 30], the output should be makeIncreasing(numbers) = false.

The initial array elements are not increasing.
By swapping the digits of numbers = 13, the array becomes [31, 31, 30] which is not strictly increasing;
By swapping the digits of numbers = 31, the array becomes [13, 13, 30] which is not strictly increasing;
By swapping the digits of numbers = 30, the array becomes [13, 31, 3] which is not strictly increasing;
So, it's not possible to obtain a strictly increasing array, and the answer is false.

Input/Output

[execution time limit] 4 seconds (php)

[input] array.integer numbers

An array of non-negative integers.

Guaranteed constraints:
1 ≤ numbers.length ≤ 103,
0 ≤ numbers[i] ≤ 103.

[output] boolean

Return true if it is possible to obtain a strictly increasing array by applying the digit-swap operation at most once, and false otherwise.

function makeIncreasing(\$numbers) {
\$hasChanged = false;
for(\$i=1; \$i< count(\$numbers); \$i++){
if(\$numbers[\$i] > \$numbers[\$i-1]){
continue;
}
if(\$numbers[\$i] < 10 && \$numbers[\$i-1]< 10){
return false;
}
\$before = \$i >= 2 ? \$numbers[\$i-2] : 0;
if(swapNumberSuccess(\$before, \$numbers[\$i-1], \$numbers[\$i]) && (!\$hasChanged)){
\$hasChanged = true;
continue;
}else{
return false;
}
}
return true;
}

function swapNumberSuccess(\$number0, \$number1, \$number2){
echo \$number1,',', \$number2, PHP_EOL;
if(\$number1 == 1000){
\$min_1 = 1;
}elseif(\$number1/100 > 1){
\$d1=floor(\$number1/100);
\$d2=(floor(\$number1/10)%10);
\$d3=\$number1%10;
\$d_min = min(\$d1, \$d2, \$d3);
\$d_max = max(\$d1, \$d2, \$d3);
\$d_mid = mid(\$d1, \$d2, \$d3, \$d_min, \$d_max);
\$min_1 = 100 * \$d_min + 10 * \$d_mid + \$d_max;
echo \$d_min,',', \$d_mid,',',\$d_max, PHP_EOL;
}elseif(\$number1/10 > 1){
\$d1= floor(\$number1/10);
\$d2= \$number1%10;
\$min_1 = min(\$d1, \$d2)*10 + max(\$d1, \$d2);
}else{
\$min_1 = \$number1;
}
echo \$min_1, PHP_EOL;
if(\$min_1 < \$number2 && \$min_1 > \$number0){
return true;
}

if(\$number2 == 1000){
\$max2 = 1000;
}elseif(\$number2/100 > 1){
\$d1=floor(\$number2/100);
\$d2=(floor(\$number2/10)%10);
\$d3=\$number2%10;
\$d_min = min(\$d1, \$d2, \$d3);
\$d_max = max(\$d1, \$d2, \$d3);
\$d_mid = mid(\$d1, \$d2, \$d3, \$d_min, \$d_max);
\$max_2 = 100 * \$d_max + 10 * \$d_mid + \$d_min;
}elseif(\$number2/10 > 1){
\$d1= floor(\$number2/10);
\$d2= \$number2%10;
\$max_2 = max(\$d1, \$d2)*10 + min(\$d1, \$d2);
}else{
\$max_2 = \$number2;
}
echo \$max_2, PHP_EOL;
if(\$max_2 > \$number1){
return true;
}
return false;

}

function mid(\$n1, \$n2, \$n3, \$d_min, \$d_max){
if(\$n1 < \$d_max && \$n1 > \$d_min){
return \$n1;
}

if(\$n2 < \$d_max && \$n2 > \$d_min){
return \$n2;
}

return \$n3;
}``````

### 11

``````You are given a matrix of integers field of size n × m representing a game field, and also a matrix of integers figure of size 3 × 3 representing a figure. Both matrices contain only 0s and 1s, where 1 means that the cell is occupied, and 0 means that the cell is free.

You choose a position at the top of the game field where you put the figure and then drop it down. The figure falls down until it either reaches the ground (bottom of the field) or lands on an occupied cell, which blocks it from falling further. After the figure has stopped falling, some of the rows in the field may become fully occupied.

demonstration

Your task is to find the dropping position such that at least one full row is formed. As a dropping position you should consider the column index of the cell in game field which matches the top left corner of the figure 3 × 3 matrix. If there are multiple dropping positions satisfying the condition, feel free to return any of them. If there are no such dropping positions, return -1.

Note: When falling, the 3 × 3 matrix of the figure must be entirely inside the game field, even if the figure matrix is not totally occupied.

Example

For

field =  [[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
[1, 0, 0],
[1, 1, 0]]
and

figure = [[0, 0, 1],
[0, 1, 1],
[0, 0, 1]]
the output should be findFullLine(field, figure) = 0.

The figure can be dropped only from position 0. When the figure stops falling, two fully occupied rows are formed, so dropping position 0 satisfies the condition.

example 1

For

field =  [[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[1, 1, 0, 1, 0],
[1, 0, 1, 0, 1]]
and

figure = [[1, 1, 1],
[1, 0, 1],
[1, 0, 1]]
the output should be findFullLine(field, figure) = 2.

The figure can be dropped from three positions - 0, 1, and 2. As you can see below, a fully occupied row will be formed only when dropping from position 2:

example 2

For

field =  [[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[1, 0, 0, 1],
[1, 1, 0, 1]]
and

figure = [[1, 1, 0],
[1, 0, 0],
[1, 0, 0]]
the output should be findFullLine(field, figure) = -1.

The figure can be dropped from two positions - 0 and 1, and in both cases, a fully occupied line won't be obtained:

example 3

Note that the figure could technically form a full row if it was dropped one position further to the right, but in that case the figure matrix wouldn't be fully contained with the field.

Input/Output

[execution time limit] 4 seconds (php)

[input] array.array.integer field

A matrix of integers representing the game field. It's guaranteed that at the beginning there are no fully occupied rows on the game field and that the top three rows are fully free.

Guaranteed constraints:
4 ≤ field.length ≤ 100,
3 ≤ field[i].length ≤ 100,
0 ≤ field[i][j] ≤ 1.

[input] array.array.integer figure

A matrix of integers representing the figure. It's guaranteed that the figure's occupied cells are pairwise connected and there is at least one occupied cell at the bottom row of the figure.

Guaranteed constraints:
figure.length = 3,
figure[i].length = 3,
0 ≤ figure[i][j] ≤ 1.

[output] integer

The dropping position such that a full row is formed. If there are multiple possible positions, return any of them. If there is no such position, return -1.``````

### 12

``````You are given three arrays of integers a, b, and c. Your task is to find the longest contiguous subarray of a containing only elements that appear in b but do not appear in c.

Return this longest subarray. If there is more than one longest subarray satisfying these conditions, return any of these possible subarrays.

Example

For a = [2, 1, 7, 1, 1, 5, 3, 5, 2, 1, 1, 1], b = [1, 3, 5], and c = [2, 3], the output can be longestInversionalSubarray(a, b, c) = [1, 1, 5].

There is no contiguous subarray of length 4 satisfying all the requirements:

a[0..3] = [2, 1, 7, 1] contains the number a = 7, which doesn't appear in b;
a[1..4] = [1, 7, 1, 1] contains the number a = 7, which doesn't appear in b;
a[2..5] = [7, 1, 1, 5] contains the number a = 7, which doesn't appear in b;
a[3..6] = [1, 1, 5, 3] contains the number a = 3, which does appear in c (which is prohibited);
a[4..7] = [1, 5, 3, 5] contains the number a = 3, which does appear in c;
a[5..8] = [5, 3, 5, 2] contains the number a = 3, which does appear in c;
a[6..9] = [3, 5, 2, 1] contains the number a = 3, which does appear in c;
a[7..10] = [5, 2, 1, 1] contains the number a = 2, which doesn't appear in b;
a[8..11] = [2, 1, 1, 1] contains the number a = 2, which doesn't appear in b.
There are two possible contiguous subarrays of length 3 satisfying all the requirements:

a[3..5] = [1, 1, 5]: both numbers 1 and 5 appear in b, and both of these numbers don't appear in c.
a[9..11] = [1, 1, 1]: the number 1 appears in b, and doesn't appear in c.
example

As you can see, the longest consecutive subarrays of a that fulfill the conditions are a[3..5] = [1, 1, 5] and a[9..11] = [1, 1, 1]. Both of these answers are acceptable.

For a = [1, 2, 3], b = [], and c = [], the output should be longestInversionalSubarray(a, b, c) = [].

Since b is empty, there are no elements that appear in b and not c. So the answer is [].

Input/Output

[execution time limit] 4 seconds (php)

[input] array.integer a

The first array of integers.

Guaranteed constraints:
0 ≤ a.length ≤ 105,
-109 ≤ a[i] ≤ 109.

[input] array.integer b

The second array of integers.

Guaranteed constraints:
0 ≤ b.length ≤ 105,
-109 ≤ b[i] ≤ 109.

[input] array.integer c

The third array of integers.

Guaranteed constraints:
0 ≤ c.length ≤ 105,
-109 ≤ c[i] ≤ 109.

[output] array.integer

Any of the longest contiguous subarrays of a which consists only of elements from b that don't appear in c.``````

## codesignal practice 3

### 7

``````You are given three integers in the form of strings: firstnum, secondnum, and thirdnum. Your task is to check whether it is possible to erase at most one digit from firstnum, so that the resulting string contains at least one digit, has no leading zeros and the value of thirdnum is equal to the sum of the values of firstnum and secondnum.

Return true if it's possible, otherwise return false.

Note: All three strings are provided without leading zeros.

Example

For firstnum = "10534", secondnum = "67", and thirdnum = "1120", the output should be eraseOneDigit(firstnum, secondnum, thirdnum) = true.

By erasing the 5th digit of firstnum, the result is 1053, and 1053 + 67 = 1120. So the answer is true.

For firstnum = "10000", secondnum = "67", and thirdnum = "1120", the output should be eraseOneDigit(firstnum, secondnum, thirdnum) = false.

The only possible modified values of firstnum would be 10000 (nothing was deleted), 0000 (first digit was deleted), and 1000 (any zero was deleted); none of which would produce the required sum, so the answer is false.

For firstnum = "1067", secondnum = "33", and thirdnum = "100", the output should be eraseOneDigit(firstnum, secondnum, thirdnum) = false.

We could delete the first digit of firstnum, resulting in 067 (and 67 + 33 = 100), but since in this case new firstnum value has a leading zero, it's considered invalid. So the answer is false.

For firstnum = "153", secondnum = "153", and thirdnum = "306", the output should be eraseOneDigit(firstnum, secondnum, thirdnum) = true.

Because 153 + 153 = 306, there's no need to delete a digit from firstnum, and the result is true.

Input/Output

[execution time limit] 4 seconds (php)

[input] string firstnum

A string representing an integer.

Guaranteed constraints:
2 ≤ firstnum.length ≤ 9.

[input] string secondnum

A string representing an integer.

Guaranteed constraints:
1 ≤ secondnum.length ≤ 9.

[input] string thirdnum

A string representing an integer.

Guaranteed constraints:
1 ≤ thirdnum.length ≤ 9.

[output] boolean

Return true if it's possible to erase at most one digit from firstnum such that the value of thirdnum is equal to the sum of the values of firstnum and secondnum. Otherwise return false.``````

### 8

``````You are given two arrays of integers a and b, and two integers lower and upper. Your task is to find the number of pairs (i, j) such that lower ≤ a[i] * a[i] + b[j] * b[j] ≤ upper.

Example

For a = [3, -1, 9], b = [100, 5, -2], lower = 7, and upper = 99, the output should be boundedSquareSum(a, b, lower, upper) = 4.

There are only four pairs that satisfy the requirement:

If i = 0 and j = 1, then a = 3, b = 5, and 7 ≤ 3 * 3 + 5 * 5 = 9 + 25 = 36 ≤ 99.
If i = 0 and j = 2, then a = 3, b = -2, and 7 ≤ 3 * 3 + (-2) * (-2) = 9 + 4 = 13 ≤ 99.
If i = 1 and j = 1, then a = -1, b = 5, and 7 ≤ (-1) * (-1) + 5 * 5 = 1 + 25 = 26 ≤ 99.
If i = 2 and j = 2, then a = 9, b = -2, and 7 ≤ 9 * 9 + (-2) * (-2) = 81 + 4 = 85 ≤ 99.
For a = [1, 2, 3, -1, -2, -3], b = , lower = 0, and upper = 100, the output should be boundedSquareSum(a, b, lower, upper) = 0.

Since the array b contains only one element 10 and the array a does not contain 0, it is not possible to satisfy 0 ≤ a[i] * a[i] + 10 * 10 ≤ 100.

Input/Output

[execution time limit] 4 seconds (php)

[input] array.integer a

A first array of integers.

Guaranteed constraints:
1 ≤ a.length ≤ 105,
-104 ≤ a[i] ≤ 104.

[input] array.integer b

A second array of integers.

Guaranteed constraints:
1 ≤ b.length ≤ 105,
-104 ≤ b[i] ≤ 104.

[input] integer lower

An integer representing a lower bound of a satisfiable square sum.

Guaranteed constraints:
0 ≤ lower ≤ 109.

[input] integer upper

An integer representing an upper bound of a satisfiable square sum.

Guaranteed constraints:
lower ≤ upper,
0 ≤ upper ≤ 109.

[output] integer

The number of pairs (i, j) such, that lower ≤ a[i] * a[i] + b[j] * b[j] ≤ upper. It is guaranteed that the answer fits in 32-bit value type.``````

### 9

``````Given an integer n and an array a of length n, your task is to apply the following mutation to a:

Array a mutates into a new array b of length n.
For each i from 0 to n - 1, b[i] = a[i - 1] + a[i] + a[i + 1].
If some element in the sum a[i - 1] + a[i] + a[i + 1] does not exist, it should be set to 0. For example, b should be equal to 0 + a + a.
Example

For n = 5 and a = [4, 0, 1, -2, 3], the output should be mutateTheArray(n, a) = [4, 5, -1, 2, 1].

b = 0 + a + a = 0 + 4 + 0 = 4
b = a + a + a = 4 + 0 + 1 = 5
b = a + a + a = 0 + 1 + (-2) = -1
b = a + a + a = 1 + (-2) + 3 = 2
b = a + a + 0 = (-2) + 3 + 0 = 1
So, the resulting array after the mutation will be [4, 5, -1, 2, 1].

Input/Output

[execution time limit] 4 seconds (php)

[input] integer n

An integer representing the length of the given array.

Guaranteed constraints:
1 ≤ n ≤ 103.

[input] array.integer a

An array of integers that needs to be mutated.

Guaranteed constraints:
a.length = n,
-103 ≤ a[i] ≤ 103.

[output] array.integer

The resulting array after the mutation.``````

## codesignal practice 2

### 4

``````Given an array of integers a, your task is to count the number of pairs i and j (where 0 ≤ i < j < a.length), such that a[i] and a[j] are digit anagrams.

Two integers are considered to be digit anagrams if they contain the same digits. In other words, one can be obtained from the other by rearranging the digits (or trivially, if the numbers are equal). For example, 54275 and 45572 are digit anagrams, but 321 and 782 are not (since they don't contain the same digits). 220 and 22 are also not considered as digit anagrams, since they don't even have the same number of digits.

Example

For a = [25, 35, 872, 228, 53, 278, 872], the output should be digitAnagrams(a) = 4.

There are 4 pairs of digit anagrams:

a = 35 and a = 53 (i = 1 and j = 4),
a = 872 and a = 278 (i = 2 and j = 5),
a = 872 and a = 872 (i = 2 and j = 6),
a = 278 and a = 872 (i = 5 and j = 6).
Input/Output

[execution time limit] 4 seconds (php)

[input] array.integer a

An array of non-negative integers.

Guaranteed constraints:
1 ≤ a.length ≤ 105,
0 ≤ a[i] ≤ 109.

[output] integer64

The number of pairs i and j, such that a[i] and a[j] are digit anagrams.``````

### 5

``````You are given an array of strings arr. Your task is to construct a string from the words in arr, starting with the 0th character from each word (in the order they appear in arr), followed by the 1st character, then the 2nd character, etc. If one of the words doesn't have an ith character, skip that word.

Return the resulting string.

Example

For arr = ["Daisy", "Rose", "Hyacinth", "Poppy"], the output should be readingVertically(arr) = "DRHPaoyoisapsecpyiynth".

First, we append all 0th characters and obtain string "DRHP";
Then we append all 1st characters and obtain string "DRHPaoyo";
Then we append all 2nd characters and obtain string "DRHPaoyoisap";
Then we append all 3rd characters and obtain string "DRHPaoyoisapaecp";
Then we append all 4th characters and obtain string "DRHPaoyoisapaecpyiy";
Finally, only letters in the arr are left, so we append the rest characters and get "DRHPaoyoisapaecpyiynth";
example

For arr = ["E", "M", "I", "L", "Y"], the output should be readingVertically(arr) = "EMILY".

Since each of these strings have only one character, the answer will be concatenation of each string in order, so the answer is EMILY.

Input/Output

[execution time limit] 4 seconds (php)

[input] array.string arr

An array of strings containing alphanumeric characters.

Guaranteed constraints:
1 ≤ arr.length ≤ 100,
1 ≤ arr[i].length ≤ 100.

[output] string

Return the resulting string.``````

### 6

``````Given an integer n and an array a of length n, your task is to apply the following mutation to a:

Array a mutates into a new array b of length n.
For each i from 0 to n - 1, b[i] = a[i - 1] + a[i] + a[i + 1].
If some element in the sum a[i - 1] + a[i] + a[i + 1] does not exist, it should be set to 0. For example, b should be equal to 0 + a + a.
Example

For n = 5 and a = [4, 0, 1, -2, 3], the output should be mutateTheArray(n, a) = [4, 5, -1, 2, 1].

b = 0 + a + a = 0 + 4 + 0 = 4
b = a + a + a = 4 + 0 + 1 = 5
b = a + a + a = 0 + 1 + (-2) = -1
b = a + a + a = 1 + (-2) + 3 = 2
b = a + a + 0 = (-2) + 3 + 0 = 1
So, the resulting array after the mutation will be [4, 5, -1, 2, 1].

Input/Output

[execution time limit] 4 seconds (php)

[input] integer n

An integer representing the length of the given array.

Guaranteed constraints:
1 ≤ n ≤ 103.

[input] array.integer a

An array of integers that needs to be mutated.

Guaranteed constraints:
a.length = n,
-103 ≤ a[i] ≤ 103.

[output] array.integer

The resulting array after the mutation.``````

## UUID理解

### 简单说明

V2、V5可以理解为V1、V3的升级版本

V1/V2 基于timestamp+MAC生成,V2加上域名
V3/V5 基于输入的namespace和值生成，v3(md5)v5(sha1)可重复生成; 如用户根据用户信息生成用户唯一id
V4 根据伪随机数生成

### UUID V3/4/5的PHP实现

``````<?php
class UUID {
public static function v3(\$namespace, \$name) {
if(!self::is_valid(\$namespace)) return false;

// Get hexadecimal components of namespace
\$nhex = str_replace(array('-','{','}'), '', \$namespace);

// Binary Value
\$nstr = '';

// Convert Namespace UUID to bits
for(\$i = 0; \$i < strlen(\$nhex); \$i+=2) {
\$nstr .= chr(hexdec(\$nhex[\$i].\$nhex[\$i+1]));
}

// Calculate hash value
\$hash = md5(\$nstr . \$name);

return sprintf('%08s-%04s-%04x-%04x-%12s',

// 32 bits for "time_low"
substr(\$hash, 0, 8),

// 16 bits for "time_mid"
substr(\$hash, 8, 4),

// 16 bits for "time_hi_and_version",
// four most significant bits holds version number 3
(hexdec(substr(\$hash, 12, 4)) & 0x0fff) | 0x3000,

// 16 bits, 8 bits for "clk_seq_hi_res",
// 8 bits for "clk_seq_low",
// two most significant bits holds zero and one for variant DCE1.1
(hexdec(substr(\$hash, 16, 4)) & 0x3fff) | 0x8000,

// 48 bits for "node"
substr(\$hash, 20, 12)
);
}

public static function v4() {
return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',

// 32 bits for "time_low"
mt_rand(0, 0xffff), mt_rand(0, 0xffff),

// 16 bits for "time_mid"
mt_rand(0, 0xffff),

// 16 bits for "time_hi_and_version",
// four most significant bits holds version number 4
mt_rand(0, 0x0fff) | 0x4000,

// 16 bits, 8 bits for "clk_seq_hi_res",
// 8 bits for "clk_seq_low",
// two most significant bits holds zero and one for variant DCE1.1
mt_rand(0, 0x3fff) | 0x8000,

// 48 bits for "node"
mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
);
}

public static function v5(\$namespace, \$name) {
if(!self::is_valid(\$namespace)) return false;

// Get hexadecimal components of namespace
\$nhex = str_replace(array('-','{','}'), '', \$namespace);

// Binary Value
\$nstr = '';

// Convert Namespace UUID to bits
for(\$i = 0; \$i < strlen(\$nhex); \$i+=2) {
\$nstr .= chr(hexdec(\$nhex[\$i].\$nhex[\$i+1]));
}

// Calculate hash value
\$hash = sha1(\$nstr . \$name);

return sprintf('%08s-%04s-%04x-%04x-%12s',

// 32 bits for "time_low"
substr(\$hash, 0, 8),

// 16 bits for "time_mid"
substr(\$hash, 8, 4),

// 16 bits for "time_hi_and_version",
// four most significant bits holds version number 5
(hexdec(substr(\$hash, 12, 4)) & 0x0fff) | 0x5000,

// 16 bits, 8 bits for "clk_seq_hi_res",
// 8 bits for "clk_seq_low",
// two most significant bits holds zero and one for variant DCE1.1
(hexdec(substr(\$hash, 16, 4)) & 0x3fff) | 0x8000,

// 48 bits for "node"
substr(\$hash, 20, 12)
);
}

public static function is_valid(\$uuid) {
return preg_match('/^\{?[0-9a-f]{8}\-?[0-9a-f]{4}\-?[0-9a-f]{4}\-?'.
'[0-9a-f]{4}\-?[0-9a-f]{12}\}?\$/i', \$uuid) === 1;
}
}
``````

## PHP实现随机红包

``````    //随机红包(总份数、最大金额、最小金额、总数)
protected function random_redpaper(\$total, \$max, \$min, \$sum){
\$sum = \$sum * 100;
//按分单位，后面全部用整数金额

\$users = array_fill(0, \$total, \$min);
\$left = \$sum - \$min * \$total;

//将剩余金额按rand(1, ceil(\$left/\$total))每次进行随机分配, \$left 小于50直接分配完成
for(;\$left > 0;){
\$amount = \$left > 50 ? rand(1, ceil(\$left/\$total)) : \$left;
\$user_index = rand(0, \$total-1);
if(\$users[\$user_index] + \$amount > \$max){
\$amount = \$max - \$users[\$user_index];
\$users[\$user_index] = \$max;
}else{
\$users[\$user_index] += \$amount;
}
\$left -= \$amount;
}

//恢复按元单位
foreach(\$users as &\$user){
\$user = \$user/100;
}
return \$users;
}``````

## centos7 yum 安装 rabbitMQ

### Install on Older Distributions (CentOS 7, RHEL 7) Using PackageCloud Yum Repository

#### 添加sign

``````## primary RabbitMQ signing key
## modern Erlang repository
rpm --import https://packagecloud.io/rabbitmq/erlang/gpgkey
## RabbitMQ server repository
rpm --import https://packagecloud.io/rabbitmq/rabbitmq-server/gpgkey``````

#### 添加repo

``````##
## Zero dependency Erlang
##

[rabbitmq_erlang]
name=rabbitmq_erlang
baseurl=https://packagecloud.io/rabbitmq/erlang/el/7/\$basearch
repo_gpgcheck=1
gpgcheck=1
enabled=1
# PackageCloud's repository key and RabbitMQ package signing key
gpgkey=https://packagecloud.io/rabbitmq/erlang/gpgkey
sslverify=1
sslcacert=/etc/pki/tls/certs/ca-bundle.crt

[rabbitmq_erlang-source]
name=rabbitmq_erlang-source
baseurl=https://packagecloud.io/rabbitmq/erlang/el/7/SRPMS
repo_gpgcheck=1
gpgcheck=0
enabled=1
gpgkey=https://packagecloud.io/rabbitmq/erlang/gpgkey
sslverify=1
sslcacert=/etc/pki/tls/certs/ca-bundle.crt

##
## RabbitMQ server
##

[rabbitmq_server]
name=rabbitmq_server
baseurl=https://packagecloud.io/rabbitmq/rabbitmq-server/el/7/\$basearch
repo_gpgcheck=1
gpgcheck=1
enabled=1
# PackageCloud's repository key and RabbitMQ package signing key
gpgkey=https://packagecloud.io/rabbitmq/rabbitmq-server/gpgkey
sslverify=1
sslcacert=/etc/pki/tls/certs/ca-bundle.crt

[rabbitmq_server-source]
name=rabbitmq_server-source
baseurl=https://packagecloud.io/rabbitmq/rabbitmq-server/el/7/SRPMS
repo_gpgcheck=1
gpgcheck=0
enabled=1
gpgkey=https://packagecloud.io/rabbitmq/rabbitmq-server/gpgkey
sslverify=1
sslcacert=/etc/pki/tls/certs/ca-bundle.crt

#### 更新yum

``yum update -y``

``Delta RPMs disabled because /usr/bin/applydeltarpm not installed``

``````yum install deltarpm
yum clean all
yum update -y``````

#### 执行安装

``````yum install socat logrotate -y
yum install erlang rabbitmq-server -y``````

## 关联单次查询 vs 单表多次查询

### 讨论

• 代码复用
如果用join的话大部分代码都无法重复使用，每次都要对每个表的查询条件重新编辑，分表查胜出。

• 消耗资源不同
用联表查询把任务都交给数据库处理，数据库处理的压力会变大，而且使用事务的话可能会锁表锁行，影响并发性能。
而使用分表查询，由于需要与数据库多次切换，会增加与数据库IO操作的开销。

• 筛选分页
这种情况下单表查询就很吃力了，感觉只能把分表的筛选条件作为主表的冗余字段来查询。
不然还是用联表查询比较好了。

• 分库分表
这种感觉就只能选择分表查询了吧？

## 灵魂画师   ## 制作一个通过wifi联网，可以远程控制的小车（二）

### 先搞一下舵机控制

https://components101.com/motors/mg996r-servo-motor-datasheet PWM的位数设置为10,精度2^10=1024,那么有效占空比就是51-102，51时0°，102时120° ``````const int freq = 50;
const int ledChannel = 0;
const int resolution = 10;//精度1024
``````

setup里面设置

``````ledcSetup(ledChannel, freq, resolution);
ledcAttachPin(ledPin, ledChannel);``````

loop里面控制舵机来回摇

``````  for(int i=0; i<120; i+=5){
ledcWrite(ledChannel, map(i, 0, 180, 51, 102));
get_pwm_info();
delay(500);
}

for(int i=120; i>0; i-=5){
ledcWrite(ledChannel, map(i, 0, 180, 51, 102));
get_pwm_info();
delay(500);
}``````

``````#include <WiFi.h>
#include <Ethernet.h>
#include <PubSubClient.h>

const char* ssid     = "***";
int currentDirection = 90;

const int freq = 50;
const int ledChannel = 0;
const int resolution = 10;//精度1024

const int ledPin = 5;

WiFiClient wifiClient;
PubSubClient client(wifiClient);

void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
int signal;
for (int i=0;i<length;i++) {

digitalWrite(4, HIGH);
}

digitalWrite(4, LOW);
}

}

}
}
Serial.println();
}

void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("arduinoClient")) {
Serial.println("connected");
// Once connected, publish an announcement...
client.publish("outTopic","hello world");
// ... and resubscribe
client.subscribe("inTopic");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}

void setup()
{
Serial.begin(115200);
delay(10);

// We start by connecting to a WiFi network

Serial.println(ssid);
Serial.print("Connecting to ");
Serial.println(ssid);

while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}

Serial.println("");
Serial.println("WiFi connected");
Serial.println(WiFi.localIP());

client.setServer("*.*.*.*", 1883);
client.setCallback(callback);

pinMode(4, OUTPUT);

ledcSetup(ledChannel, freq, resolution);
ledcAttachPin(ledPin, ledChannel);
}

void loop()
{
//  if (!client.connected()) {
//    reconnect();
//  }
//
//  client.loop();

//周期20ms, 有效占空比是1ms-2ms,1ms时0°，2ms时120°
//精度2^10=1024,那么有效占空比就是51-102，51时0°，102时120°
//90°时就是(51+102)/2 = 76
//  ledcWrite(ledChannel, 76);

for(int i=0; i<120; i+=5){
ledcWrite(ledChannel, map(i, 0, 120, 51, 102));
get_pwm_info();
delay(500);
}

for(int i=120; i>0; i-=5){
ledcWrite(ledChannel, map(i, 0, 120, 51, 102));
get_pwm_info();
delay(500);
}
}``````

## 制作一个通过wifi联网，可以远程控制的小车（一）

### 硬件

ESP32 连接wifi，提供网络通信能力
L298P 电机驱动，可以同时驱动两路直流电机，11V供电，然后将5V供电再提供给ESP32。   ### 软件方面

ESP32上 建立mqtt客户端，通过云端broker和控制端利用发布订阅方式通信。

arduinoIDE用到的库:
WIFI -- 连接wifi
SubPubClient -- mqtt发布订阅客户端

### 实际操作

``````void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
if(m == 'b'){
digitalWrite(4, HIGH);
}

if(m == 'a'){
digitalWrite(4, LOW);
}
Serial.println(m);
Serial.println();
}``````

``````#include <WiFi.h>
#include <Ethernet.h>
#include <PubSubClient.h>

const char* ssid     = "***";

WiFiClient wifiClient;
PubSubClient client(wifiClient);

void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
if(m == 'b'){
digitalWrite(4, HIGH);
}

if(m == 'a'){
digitalWrite(4, LOW);
}
Serial.println(m);
Serial.println();
}

void reconnect() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
if (client.connect("arduinoClient")) {
Serial.println("connected");
client.publish("outTopic","hello world");
client.subscribe("inTopic");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}

void setup()
{
Serial.begin(115200);
delay(10);

// We start by connecting to a WiFi network

Serial.println(ssid);
Serial.print("Connecting to ");
Serial.println(ssid);

while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}

Serial.println("");
Serial.println("WiFi connected");
Serial.println(WiFi.localIP());

client.setServer("81.*.*.*", 1883);
client.setCallback(callback);

pinMode(4, OUTPUT);
}

void loop()
{
if (!client.connected()) {
reconnect();
}
client.loop();
}``````