title: Informatik

#+STARTUP: overview

Informatik


title: MachineLearning

#+STARTUP: overview

Math for ML

Self Entropy

One thing happens, how much information can be persent. how meanful it is

Information Entropy

cross Enteopy

Conditional enteopy

Under the condition than Y has been happened, estimate the Enteopy of X to be happened

Gini

吉尼系数

KL

the difference between p and q

Matrix

Conjugate transpose Matrix

共轭转置矩阵, 先共轭再转置,还是先转置再共轭都可以。

Normal Matrix

正定矩阵, 是转置和本身满足交换律 可酉变换

Unitary Matrix

酉矩阵,是正定矩阵, 即转置和本身满足交换律,而且等于 I

orthogonal matrix

实数酉矩阵

得该矩阵的转置矩阵为其逆矩阵

Hermitian matrix

, 共轭对称 埃尔米特矩阵,厄米特矩阵,厄米矩阵,所有元素对称出共轭

Eigenwertzerlegung eigende decompostion

对于矩阵求特征值特征向量,特征值分解,但是要求必须是方阵,如果不是,先 要转换: A = a*a.T

import numpy as np
a = np.mat([[1,2,3,4],[1,1,1,1]])
A = a*a.T
B, U = np.linalg.eig(A)
print("eigenvalue of A : ")
print(B)
print("eigenvalue of a :(should be equal to the following) ")
print(np.sqrt(B))
print("eigenvactor : ")
print(U)

SVD Singular value decompostion

但是对于一般矩阵,不是方阵,可以奇异值分解:

import numpy as np
a = np.mat([[1,2,3,4],[1,1,1,1]])
U, B, Vt = np.linalg.svd(a)
print("left eigenvalue : ")
print(U)
print("eigenvactor of a : ")
print(B)
print("right eigenvalue : ")
print(Vt)

Bayes's Rule

if x and y are independent:

条件概率:
条件概率 = 联合概率/边缘概率
先验概率和后验概率都是条件概率,但是条件已知是先验

全概率公式

贝叶斯公式

贝叶斯公式 + 全概率公式 + 条件概率
\begin{eqnarray*}
P(A|B) &= \frac{P(B|A)P(A)}{P(B)} \\
       &= \frac{P(B|A)P(A)}{\sum_{i=1}^{n} p(B,A_{i})} \\
       &= \frac{P(B|A)P(A)}{\sum_{i=1}^{n} P(B|A_{i})P(A)} \\
\end{eqnarray*}

Kovarianz Matrix

for i = {1...n}, is a random variable, which belongs to Gaussian distribution

set

co-variance matrix

\begin{equation}
\Sigma =
  \left(
  \begin{array}{c}
          x_{1}-\bar{x}_{1} \\
          x_{2}-\bar{x}_{2} \\
          x_{3}-\bar{x}_{3} \\
          ..                \\
          x_{n}-\bar{x}_{n}
 \end{array}
 \right)
  \left(
  \begin{array}{ccccc}
          x_{1}-\bar{x}_{1} &
          x_{2}-\bar{x}_{2} &
          x_{3}-\bar{x}_{3} &
          ..                &
          x_{n}-\bar{x}_{n}
  \end{array}
  \right)
\end{equation}

对角线上是对应元素的方差,其他是相对于两个元素的协方差

Regularization

L Regularization is the weight in network, it's a scalar


N example number M Eigenschaften Number, Diemension number L0 控制网络中的非零权重 L1 网络中的所有元素的绝对值之和,促使网络生成更多的稀疏矩阵 L2 网络中的所有元素平方和,促使网络生成小比重的权值 w w~1~, w~2~ q=1 l1 regularization q=2 l2 regularization λ learning rate 依据w的同心圆 q=1, 菱形, q=2, 圆形


Loss 要最小,part1 刚好和 part2 相接,l1会在坐标轴上,所以如果有较小分 量,会被直接设为0

Error Bias-Variance-trade-off

Error = Bias + Variance + noise

Bias 偏差 欠拟合 发挥,观测等主观因素影响
Variance 方差 过过拟合 稳定性,模型的构建决定
noise 噪音 统难度


Multi variable Gaussian distribution

seeing the link 知乎


def gaussian(x,mean,cov):
    dim = np.shape(cov)[0] #维度
    #之所以加入单位矩阵是为了防止行列式为0的情况
    covdet = np.linalg.det(cov+np.eye(dim)*0.01) #协方差矩阵的行列式
    covinv = np.linalg.inv(cov+np.eye(dim)*0.01) #协方差矩阵的逆
    xdiff = x - mean
    #概率密度
    prob = 1.0/np.power(2*np.pi,1.0*dim/2)/np.sqrt(np.abs(covdet))*np.exp(-1.0/2*np.dot(np.dot(xdiff,covinv),xdiff))
    return prob

Mahalanobis distance

马氏距离所使用的变换 : ,

关于新的坐标,U 是变换的旋转, 是基底的延伸, 是在其 上的投影,此后,在新坐标上,即为多变量,标准,不相关高斯分布

K-fold Cross Validation


N total examples K number of sub-fold m number of each sub-fold big K small bias, with over fitting, big variance small K big bias, without fitting, low variance


confusion matrix


                 Actually Ture   Actually False

predict Positive TP FP predict Negative FN TN


Ture Positive Rate (recall)

namely, Ture Positive Rate, y axes of ROC

False Postive Rate

namely, false Position, x axes of ROC

ROC Receivert Operator Characteristic

under the acceptable x (1 - Sensitivity) , we want the best y (Sensitivity). from side to side is all classifed to Positive to all classifed to negative

AUC Area under the Curve

je mehr Fachsgebiet, desto besser for the Method, we use this target to choice our Method

F1

harmonic mean of recall and precision

关联性属性 : 高中低 (3,2,1) 非关联性属性: 猪狗羊 ((1,0,0), (0,1,0),(0,0,1))

Macro Micro Average

This is for non-binary classification at frist calcalete for all feather the confusion matrix als binary classification

Macro Average

Micro Average

Jacobin matrix

for , 由球坐标系到直角坐标系的转化由 F: ℝ+ × [0, π] × [0, 2π) → ℝ3 函数给出, 其分量为: 此坐标变换的雅可比矩阵是 其雅可比行列式为 r2 sin θ,由于 dV = dx dy dz,如果做变数变换的话其体 积元(Volume element),dV,会变成:dV = r2 sin θ dr dθ dφ。

预剪枝和后剪枝

在利用训练集的最大信息增益确定划分属性后,用验证集来检验划分,如果验证 集的信息熵增加,(泛化结果不好)否定此次划分,设为叶节点

后剪枝是在这个树完成后,用验证集去检验每一个内节点,从下到上,如果去掉 该划分有更小的信息熵,则废除该划分。

属性有连续值和缺失值

连续值离散化:排列该属性的所有取值n个,在n-1个区间中去中间值为离散值, 遍历所有离散值,找到最大信息增益的离散值,作二分。

缺失值,取出该属性的非缺失子集,再配以相应的比率计算信息增益,处理和以 前一样。如果选出的划分属性有缺失值,则给划分不作用到缺失样本,复制到每 个划分子集

activation function

activation

输出为实数空间或某个区间, 连续变化。直接有输出值和真实值比较

Sigmoid

导数:

ReLU

LeakyReLU

Tanh

导数:

MSE

导数 :

inf entropy

softmax

所有种类的概率之和为1 导数:

cross entropy

在计算交叉熵时, 一般是和 softmax 函数一起使用的

for One-hot coding 为1 时,预测正确,交叉熵为0。 导数:

用上面 softmax 的导数结果,分为k=i 和k!=i两种情况

This is why Cross Enterpy can train the loss very fast. if a is far away from y, the update will be its difference

example bagging

多次放回抽样,用不同抽样的数据集在多棵树上并行计算,


More Tree Bias remained Variance reduce to limit


所以刚开始选择偏差小,方差大的强模型

Boosting

固定数据集,在多个串行的模型上顺序计算,模型间强相关,防止过拟合,用弱 相关模型

gradient decent

当数据点很多是,正则化方法计算量将非常大,此时较多使用梯度下降

sklearn API

import numpy as np
import random
from sklearn import linear_model
testsize = 5

x = np.array([a for a in range(100)])
onesx = np.ones(x.shape)
X = np.c_[x, 2*x, onesx]
y = np.array([a*5 + 20 + random.randint(0,3) for a in range(100)])
print("the X shape is {}, and y shape is {}".format(X.shape, y.shape))

# Sklearn API
reg = linear_model.LinearRegression()
model = reg.fit(X,y)
print("Sklearn: the weith is {}, and the intercept is {}".format(model.coef_[:-1] ,model.intercept_))
print("the predect of 3 ele is {}".format(model.predict(np.c_[np.arange(testsize), np.arange(testsize),np.ones(testsize)])))


# manual
def featureNormalize(X):
    (m,n) = X.shape
    X_norm = X
    mu = np.zeros(n);
    sigma = np.zeros(n);
    for i in range(n):
        mu[i] = np.mean(X[:,i])
        sigma[i] = np.std(X[:,i])
        X_norm[:,i] = (X_norm[:,i]-mu[i])/sigma[i]
    return X_norm
def computeCost(X, y, theta):
    return np.sum((np.dot(X,theta) -y)**2)/(2*len(y));

def gradientDescent(X, y, theta, alpha, num_iters):
    m = len(y)
    J_history = np.zeros(num_iters);
    theta_len = len(theta);
    for num_iter in range(num_iters):
        theta = theta - (alpha/m)*np.dot(X.T,(np.dot(X,theta).reshape(-1)-y))
        J_history[num_iter] = computeCost(X, y, theta)
    return theta, J_history

alpha = 0.0001
num_iters = 400000
theta = np.zeros(2+1)
theta, J_history = gradientDescent(X, y, theta, alpha, num_iters)
print("Greadient decent: the weight is {}, and the intercept is {}".format(theta[:-1],theta[-1]))
print("the predect of 3 ele is {}".format(np.dot(np.c_[np.arange(testsize), np.arange(testsize),np.ones(testsize)], theta)))

Ordinary Least Squares(OLS)

正规化方程

正则化方程的推导,用高斯分布的多变量分布的Maxisum likelihood,能一起求得对weight和bias值 :

但是要添加一列1到 train 和 test,至于在前面还是后面有点怪异。

目前认为,在后面的话,多变量和参数可以按需求访问

Loss function: 求导,并令其为0, 但是要求 必须可逆。

正则化正规化方程

import numpy as np
import random
from sklearn import linear_model
testsize = 5

x = np.array([a for a in range(100)])
onesx = np.ones(x.shape)
X = np.c_[x,onesx]
y = np.array([a*5 + 20 + random.randint(0,3) for a in range(100)])
print("the X shape is {}, and y shape is {}".format(X.shape, y.shape))

# weight = np.dot(np.dot(np.linalg.pinv(np.dot(X.T, X)), X.T), y)
weight = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(y)

print("OLS : the weight is{}, and the bais is {} ".format(weight[:-1], weight[-1]))
print("the predect of 5 ele is {}".format(np.dot(np.c_[np.arange(testsize),np.ones(testsize)], weight)))


也可以是对变量 with multi variables
import numpy as np
import random
from sklearn import linear_model
testsize = 5

x = np.array([a for a in range(100)])
onesx = np.ones(x.shape)
X = np.c_[onesx, x, 2*x]
y = np.array([a*5 + 20 + random.randint(0,3) for a in range(100)])
print("the X shape is {}, and y shape is {}".format(X.shape, y.shape))

# ordinary  least squares (正规化方法)
weight = np.dot(np.dot(np.linalg.pinv(np.dot(X.T, X)), X.T), y)
print("OLS : the weight is{}, and the bais is {} ".format(weight[:-1], weight[-1]))
print("the predect of 5 ele is {}".format(np.dot(np.c_[np.arange(testsize), np.arange(testsize),np.ones(testsize)], weight)))


Lasso regression

we reform the Loss function from OLS as and add the regularity term (Manhattan norm) of Lasso regression put all together, for Lasso regession:

the minimun of should be a the interaction of the first term, which is the solution of OLS and the second term, which is the Lasso regularity term.

This reduce many feather coefficient to be 0,

Ridge regression

we reform the Loss function from OLS as and add the regularity term of (Euclidean norm) Lasso regression put all together, for Lasso regession:

the minimun of should be a the interaction of the first term, which is the solution of OLS and the second term, which is the Ridge regularity term.

This reduce many feather coefficient to be as small as possible

Elastic Net regression

combinate Lasso regession and Ridge regression

Decision List

(f1,v1),(f2,v2)....(fr,vr) fi is a term in CNF, vi belongs {0,1}, and the last term fr is always true. and each term can be viewed as if else extended. if fi is matched, so vi is its value.

for 0<k<n, k-CNF and k-DNF are proper

linear regression

linear Discriminate Analysis

Fisher's linear discriminant

输入为j=0,1类样本,每类分别 个样本 ,

Fisher's linear discriminant with Kernel method

Numerator: Denominator:

Probabilistic Generative Model

用贝叶斯定理求出每个可能的概率,再取最大的值

one two class case

即可以 Logistic sigmoid 函数求解

multi class case

即可以用 Softmax funtion 来求解

Probabilistic Discriminant Model

Better predictive performance if assumptions about class-conditional distributions not correct.

和 generative model 一样求解,同样也有二分和多分类,但是该类问题设为 logical regression, See logical regression

Principe Component Analysis

PCA Algorithms

将原来的数据坐标进行线性组合,组成新的坐标基底,让数据在新基底 上投影最小化,以去除,压缩该些维度

  1. 将数据中心化
  2. 求出数据在所有特性的协方差矩阵
  3. 如果矩阵是方阵,则可以直接特征值分解
  4. 如果矩阵不是方阵,则先乘以转置,再特征值分解,注意此时求得特征值要开方
  5. 如果不是方阵,也可以直接奇异值分解
  6. 取出前面的需要的维度,多余的被压缩了

Probabilistic generative model for PCA

State the probabilistic generative model underlying Probabilistic PCA with a K-dimensional latent space and observations . Define all three random variables and their distribution.

Hidden Variable z in K-dimension from probabilistic generative PCA: we can transfer z into standard gaussian distribution,

observation variable x in D-dimension giving z:

So,

K-Nearest Neighbor [[classification]{.smallcaps}]{.tag tag-name="classification"}

This is based on the idea that instances of the same class are close to each othera

Algorithms

selecting the k nearest neighbor from the new instance, and leabel it as the majority target from k nearest neighbor instance

Decision tree [[classification]{.smallcaps}]{.tag tag-name="classification"}

to find the "most informative feature"

Algorithms

在训练集内以最大信息增益来确定划分属性,在各个子区内再重复剩下的属性 信息熵增益 = Entropy - conditional Entropy

For all remained feathers, get the biggest Gain(D, a) for one feather, and using this feather as Criteria for the classification. over this again and again

Random Forest [[classification]{.smallcaps}]{.tag tag-name="classification"}

combining multiple decision trees into a single classifier. Random Forest = Decision Tree + Bagging + random Eigenschaften


More deeper Bias reduce More Eigenschaft Bias reduce


algorithms on decision tree

1, examples randomization for training 2, features randomization for training

Naivi Bayes's [[classification]{.smallcaps}]{.tag tag-name="classification"}

For can be calcaleted with Multinomial Navie Bayes and Graussian Navie Bayes, later one is better for continuons examples

假设各个属性完全独立的条件下

要计算在某些条件下某个事件出现的概率(分数)等于
在每个条件下该事件发生的条件概率的连乘再乘以该事件发生的总概率
再计算在同样的条件下该事件不出现的概率,再归一化

最后谁大选谁(注意样本不足引起的某属性的条件为零)

logistic regression [[classification]{.smallcaps}]{.tag tag-name="classification"}

Odd

, which is the probability of x happen to it not happen

fit logit with linear regression:

Odd ratio

Odd ratio of :

if Odd ratio eqaul 2, means when feather x increase by one, Odd will increase 2.

if Odd ratio bigger than one, Odd increase if x increase if Odd ratio smaller than one, Odd decrease if x increase

algorithms

Logistic regression tries to estimate the logarithm of odds that an instance belongs to a class
i.e., that is nothing else but the logarithm of the odds that the instance is of that class.

This is also the same form of sigmoid function 用 logical sigmoid function 来作二分类判断,检验概率是否过半

Support Vector Machine [[classification]{.smallcaps}]{.tag tag-name="classification"}

without soft margin

对于点的划分,由decision theory: 距此线一个单位对点标注 then y = then y = -1 So, 最大化标+点和标-点的距离: 等价于最小化, 再加上约束条件 设L对w和b的偏导为0,,. 再代回L,

with soft margin

对于不能绝对线性分割的,可以允许某些点进入空白分割区域(从-1到1的区域)


slack variable Controls trade-off between slack and margin C , if misclassified


this L satisfied the KKT condition, and can be solved.


good classified a = 0 ϵ = 0 C = 0 on the margin a < C ϵ = 0
violate the margin a = C ϵ > 0
misclassified ϵ > 1


kernel function

high dimension separable

Neural network [[classification]{.smallcaps}]{.tag tag-name="classification"}

Backpropagation

感知机

对x的向后更正,. 对于感知机的传递功能,. 由于感知机没有激活函数,所以直接对.

多层神经网络

而对于多层神经网络,, , . 每层之间具有激活函数, , . 损失函数, ,

如果对于多层神经网络,则需要逐层计算,其中 中的w就是相应层的权重,由最后的 L逐步回推到w。

K-Means [[Cluster]{.smallcaps}]{.tag tag-name="Cluster"}

K-means is an example for centroid-based clustering. We can determine the cluster of any instance as .

algothism

输入样本集 D: <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.625em;vertical-align:-0.1944em;"></span><span class="mord"><span class="mord mathnormal">x</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3011em;"><span style="top:-2.55em;margin-left:0em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mtight">1</span></span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord"><span class="mord mathnormal">x</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3011em;"><span style="top:-2.55em;margin-left:0em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mtight">1</span></span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord"><span class="mord mathnormal">x</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3011em;"><span style="top:-2.55em;margin-left:0em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mtight">2</span></span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mpunct">,,,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord"><span class="mord mathnormal">x</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.1514em;"><span style="top:-2.55em;margin-left:0em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mathnormal mtight">m</span></span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span></span></span></span>
聚类数 k,
最大迭代数 N,
期望输出: <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8778em;vertical-align:-0.1944em;"></span><span class="mord"><span class="mord mathnormal" style="margin-right:0.07153em;">C</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3011em;"><span style="top:-2.55em;margin-left:-0.0715em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mtight">1</span></span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord"><span class="mord mathnormal" style="margin-right:0.07153em;">C</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3011em;"><span style="top:-2.55em;margin-left:-0.0715em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mtight">2</span></span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mpunct">,,,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord"><span class="mord mathnormal" style="margin-right:0.07153em;">C</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3361em;"><span style="top:-2.55em;margin-left:-0.0715em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mathnormal mtight" style="margin-right:0.03148em;">k</span></span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span></span></span></span>

随机初始化k个聚类中心,并作不同类别的标记
for i= 1,2,..N:
    随机初始化所有C个中心
    计算每个点到每个中心的距离(arithmetic mean),并被最小距离的聚类中心标记,以此划分所有X
    对于所有相同标记的聚类X更新中心,再重复上一步骤,直到没有变化为止,或者达到迭代次数限制
import random
import numpy as np
import matplotlib.pyplot as plt

b = []
for i in range(100):
    a = np.array(list([(20,50),(30,10),(60,30)]))
    for j in range(a.shape[0]):
        for k in range(a.shape[1]):
            a[j][k] += random.randint(0,30)
            b.append(a[j])

b = np.array(b)
plt.plot(b[:,0], b[:,1], 'ro')
plt.title("toy data")
plt.show()


# sklearn API
from sklearn.cluster import KMeans
y_pred = KMeans(n_clusters=3, random_state=9).fit_predict(b)
plt.scatter(b[:, 0], b[:, 1], c=y_pred)
plt.title("toy data with sklearn API")
plt.show()

# manual
def findClosestCentroids(X, centroids):
    distance = np.zeros((len(X),len(centroids)))
    for i in range(len(X)):
        for j in range(len(centroids)):
            distance[i,j] = np.linalg.norm(X[i,:]-centroids[j,:])
    return np.argmin(distance,axis=1)

def computeCentroids(X, idx, K):
    centroids = np.zeros((K,X.shape[1]))
    for i in range(K):
        centroids[i,:] = np.mean(X[idx == i],axis = 0)
    return centroids


def runkMeans(X,K,max_iters):
    indexs = np.random.choice(np.array(range(len(X))), K,replace=False)
    centroids = X[indexs]
    for max_iter in range(max_iters):
        idx = findClosestCentroids(X, centroids)
        centroids = computeCentroids(X, idx, K)
        colors = ['','','']
        for i in range(K):
            plt.scatter(X[idx==i, 0], X[idx==i, 1])
        plt.scatter(centroids[:, 0], centroids[:, 1], c='r')
        plt.title("toy data with manual {} time".format(max_iter))
        plt.show()
K = 3
max_iters = 3
runkMeans(b,K,max_iters)

select the best k

based on domain knowlegde:

cluster are not internally similar, increase k similar objects are in different clusters, decrease k

Visualizations

this give us a intuitive aspects

Within-Sum-of-Squares

minimizing the intra-cluster variance

Problems

1, k -Means is sensitive to the initial clusters.

2, An unsuitable value of k may lead to bad results.

3, All features must have a similar range of values,

4, Because the cluster assignment is based on the distance, clusters tend to be round.

EM algorithms for Gaussian Mixture model [[Cluster]{.smallcaps}]{.tag tag-name="Cluster"}

This concept is called distribution-based clustering. Each instance is assigned to the most likely cluster with and the initialization means random mean values and random covariance matrices at first.

k selecting

Bayesian Information Criterion for clusters K for

Algorithm

, .... for

E step: compute responsibilites given current

descripte the probabilistic of example n belongs to k distribution.

M step: update given . according to the derivative of $log p(x|π, μ, Σ) = ∑^N^n=1~log ∑^K^k=1 π N(x~k|μ~k~, Σ~k~)$with respect to the ,

cluster number:

cluster means:

cluster covariances:

cluster priors:

problem

1, This is also sensitive to the initination.

2, An unsuitable value of k may lead to bad results.

3, clusters tend to be round or ellipse, but still not suit for half mood

DBSCAN [[Cluster]{.smallcaps}]{.tag tag-name="Cluster"}

This is density-based clustering

concepts minPts

neighbors(x) = {x' X: d(x, x') <= $ϵ$}

neighbors(x) is dense if |neighbors(x)| >= minPts

core(x) = {x X: |neighbors(x)| >= minPts} called core points each dense neighbors exist at last on core point

Algorithm

1, randomly select one core point as the first cluster 2, growing the first cluster with neighbors, 3, growing again with core points in neighbors again and again 4, select the other core point as other cluster repeat

select and minpts

with largest curvature ,sharpest change in lines for difference and minPts

problems

1, difficult selection of and minPts 2, different density matters 3, scale sensitive

Single Linkage Clustering [[Cluster]{.smallcaps}]{.tag tag-name="Cluster"}

hierarchical clustering

Algorithm

1, every instance as a cluster 2, growing the distance to merge cluster to 1 cluster

problems

large storage of scalability no noise leads to small cluster scale sensitive


title: DeepLearning

#+STARTUP: overview

Batch Size Problem

Batch Gradient descent

  • all data as input once
  • loss graph is quite smooth
  • need great calculation power

Stochastic gradient descent

  • input each time only one data sample
  • cost will fluctuate over the training
  • fast update the weights

mini-batch gradient descent

  • only a subset of all data points in each

big batch size

Advantages: the descension of weights has a more accuary direction, less oscillation. Disadvantages: memery explotion, and fall into locally minimum

small batch size

Advantages: more times weights update, more chance to overcome locally minimum, Disadvantages: difficult to convergence

Learning rate


too small converge slowly or find local minimum too large oscillation or divergence


Second order optimizer

SGD with momentum

learning rate decay

Pytorch

automatic differentiation

Regularization

Multi-layer perceptrons

Perceptron

Universal Approximation Theorem Perceptrons solves linearly separable problem One hidden layer is enough to approximate any continuons funtion, to an arbitrary degree of accuracy

Perceptron Learning Algorithm(PLA): Iterate over training examples until convergence

Gradient Descent

Advance gradient descent

Gradient-based optimization does neither always find the absolute minimum, nor does it find the optimal direction

Second-order optimizers

Theorical besser performance, but generally too expensive and not work with minibatches

SGD with momentum


too small get stuck in local minimum or saddle points too large overshoot optimum or spiral around it


AdaGrad

adaptive gradient algorithm(DL~03MLP~.pdf/12 )

RMSProp

root mean square propagation(DL~03MLP~.pdf/13 )

Adam

Regularization of MLP

Dropout

Early stop

Active funtion

Sigmoids vanish for large postive and negative inputs Rectified Linear Unit(ReLu) LeakyReLU Exponential linear unit Absolute value activation

Babysitting training neural network

  • check initial loss make sense
  • overfit training model to 100% accuracy of small samples, such as few minibatches
    • adjust the initialization and learning rate
  • find the learning rate, which reduce loss significantly
  • rough train few epochs with learning rate nearby from previous step
  • use the best options from previous step, training longer
  • watch out the loss curves
    • if learning rate decay needed
    • accuracy of train vs validation, overfit, underfit, go back to step 5
  • Early strop Idea: Stop training when generalization error increases

Hyperparameter search

  • grid search and random search
  • Multipy learning rate by N where you increase the batchsize by factor of N

Data Augmentation

  • data artifacts
    • flips
    • crops and scales
    • randomize color
    • rotate
  • advance data augmentation
    • Mixup: take linear combination of input and target of two training samples
    • CutMit: mix patches of the two input, Target is linear combination with weight according to patch ratio

CNN

Modern CNN architectures tend to use strided convolutions instead of max pooling.

Output size

valid: padding: N: input size M: output size p: padding k: kernel size s: stride size

Receptive field

From where I want to calcalete to the input layer. and set the current calcalete layer's RF as 1

Zero Padding


valid without padding shape reduce k-1 same with padding shape stay the same


pooling


max pooling only chose the maximum one of block average pooling use the average of block


Feather abstact

The layer can extract image features, and finally determine the convolution kernel parameters through backpropagation to obtain the final features

Normalization

For Vanishing/exploding gradients: each example in layer all data are normalized

  • Batch Normalization norm each channel
  • Layer Normalization norm each sample
  • Instance Normalization norm each sample and each channel
  • Group Normalization norm multi channel and sample

regular convolution

Depthwise separable convolution

  • Depthwise Convolution: channel-wise
  • Pointwise Convolution: 1*1 convolution

learning rate decay

dacay schudle

Linear Warmup

small learing rate increase very fast, and decay slowly can deal with bad initialization

Modul ensembling

  • training N model, and take the averate
  • take N snapshots of training

ResNet

Vanishing gradient and exploding gradient

GAN (Generative Adersarial models)

Implicit density

step 1 Generater stay, Discriminater update

  • randomly initialization of G and D
  • inputs (Distribution: ) from known distribution to G get rough outputs (Distribution: )
  • rough outputs and real image (Examples: ) feed to D
  • training D to classify them with mark, and update D Max to 1 Min to 0, so

step 2 Discriminater stay, Generater update

  • fix D, feed new inputs from known distribution to G

  • get rough outputs again, and pass them to D, and evaluated with mark

  • training G, for getting better mark

    max to 1, so

    Just like training normal neural network with minimum cross enteopy

summary

Autoencoder

input data Feathers predicted labels predicted labels + Classifier loss function

VAE (Variational Autoencoders)

optimizes variational lower bound on likelihood Approximate density search the latent implimentation, reduce the dimensionality to capture meaningful factors in data x: examples z: latent parameters , simple gaussian prior, encoder neural network

  • decoder network
  • KL term between gaussian encoder and z latent. make approximate posterior distribution close to prior.
  • mostly similarity between q and p, KL[q(z|x)||p(z|x)], bigger than 0, so maxmized data likelihood can only have a lower bound value

Intractability of p(x), because We want , but it's too difficult, so we use as approximation:

We randomly example the z from the normal Gaussian for VAE

PixelCNN (Autoregressive models)

Explicit density, optimizes exact likelihood exact likelihood(chain rule), and training slowly maxmize likelihood Mask converlutions: kernel filter pixel in the future are set to be 0

Diffusion Model

image to noise : forward process noise to image : backward process

RNN

this is many to one, A[shape(h), shap(h)+shap(x)] is shared by all step there is no big difference for prediction with only h(t) or conta(h(1), h(t))

LSTM

many gate, output elementweise product Stacked, Bedirection

  • Forget Gate:

  • Input Gate:

  • New Value:

  • Output Gate:

  • input of C :

  • output of C :

Semi-supervised learning

train model jointly on labeled and unlabled data supervised loss, time dependent weight*unsupervised loss()

consistentcy loss SSL

consider the consistency loss on all examples between Student model and Teacher model.

  1. training the student model with labeled data as usual,
  2. difference augmented view methodes(scala, rotate...) applying on each unlabled data.
  3. passing augmented views(x', x'') of the same data(x) to student and teacher model
  4. minimizing the consistency loss of both output .
  5. updating weight of teacher model,

Pseudo-label based SSL

  1. training Teacher model with labeled data as usual
  2. using well trianed teacher model to predict unlabled data
  3. taking over the confident prediciton(threshold) lable as new labeled data
  4. training student model with original and new label data
  5. passing the student model weights to teacher model, and predict all data again

Weakly-supervised learing

use simple and cheaper labels for training

  • Classification: hashtags
  • Object detection: images tags
  • Semantic Segmentation: scribble annotations

Self-supervised learing

pre-training unsupervised model with large unlabled data, then fineturn it with small label dataset

Colorization

Reference Frame , color , Target Frame , predect color .

Context Prediciton

picture divied into patches, predict the relative position of patches.

  • Gap between batches, jitter location of patches
  • Chromatic abberation, predict the absolute position of patches

Contrastive Learning

Contrastive Predictive Coding (CPC)

Idea: Learn to predict future embeddings linearly. Loss: mean squared error not helpful, because encoding = 0 will give perfect loss, positive example are close, and negative example are distant

SimCLR

Maxmize agreement between representations of two views, good contrastive learning need many negative examples.

  • MoCo: , decouples batch size of large number of negative exsamples, more complex model
  • BYOL: no need for negative examples

Cross-model contrastive learning(CLIP)

Semantic segmentation

methods

  • in CNN model, replace the last fully connected layer with 1x1 converlutions layer
  • at last upsampling to original size
  • ouput original weight * original height * class number with one-hot coding.
  • loss funtion, cross entry of pixel-wise: ,
    • imbalanced background not work good for target prediciton, using balanced loss function
    • weight factor r inverse to class frequency
    • dice loss
    • Focal loss
  • upsampling: nearest neighbor interpolation, transposed convolutions
  • upsampling combining with the corresponding pooling

FCN

tranposed convolution can cause artifacts, can avoid by using fixed upsampling(nearest neighbor)

U-net

  • Contraction: extract semantic information
  • Expansion: produce detail segmentation
  • Skip connection: copy high-resolution information into decoder

Deep Lab

combine feathers representations at multiple scale atrous converlution: dilate filter by implicit zeros in between kenerl elements

Object Detection

Predict the Bounding box and predict the class

two stage mothode

Faster R-CNN:

  • Loss = classification loss + region proposal loss
  • RoI pooling: all object map to Rol convolutional features(C*H*W) for region proposal

single stage mothode

change the mask size, and predect all at once

Instance Segmentation

segment individual object from image Instance segmentation is invariant under relabeling

  • Proposal-based instance segmentation, perform object detection at first, the predict each mask instance with bounding box L = classification loss + region proposal loss(bounding box) + mask loss
  • proposal-free instance segmentation, predict intermediate representations,
    • foreground prediciton
    • boundary prediciton

image to image

  • colorization
  • super resolution
  • Denoising

title: NLP

#+STARTUP: overview

Data process

all input should numerical, categorized character shoud be one-hot coded, starting with 1

Tokenizationn

  • Breaking text to words (There are many steps to consider )
  • CountWordFrequencies (counted key-value dictionary)
    • list all sorted dictionary
    • if the list is too big, removing infrequent words(because of incorrection, or neame...) good for one-hot coding
  • encode to sequences
    • with counted dictionary index
    • index length is one-hot coding vector length
  • one-hot coding all sequences
    • if one-hot code vector is not so lang, word embedding is not needed
<!-- -->
tests[5] = "this is a cat and a"
tests_dict = {"this": {1:1}, "is": {2:1}, "a":{3:2}, "cat":{4:1}, "and":{5:1}}
tests_sequences = [1,2,3,4,3]

Word Embedding

compose high dimension one-hot vector to low dimension is high dimensional vector after one-hot coding(v,1) of collected data is the parameter matrix trained by data(d,v), is low dimensional vector(d,1), for further training : The dimension parameter d is important, can be vertified with corss validation. Each row of is called (words vector词向量), can be interpreted with classification

Embedding layer need the number of vocabulary(v), embedding~dim~(d), and word~num~(cuted words number) v*d : parameters for this layer

language model

skip-gram

CBOW

continuous bag of words

text generatation

Encoder: A is RNN layer or LMST layer, all input(x1 to xm) share the same A, hm is the last result, only give hm to decoder, we can generate text, but many content of input will be forget

seq2seq

After one resulte in Decode is generated, With Corss Enteopy to update the Network, using all the resulte we get, to predict the next resulte until all is finished consuming the previously generated symbols as additional input when generating the next.

Transformer

simple RNN + attention

Encoder Input E Decoder Input after RNN or LSTM we get Now unlike before only pass the last element to Decoder, we use attention skill to mix all input information

  1. Notion:

    • Encoder, lower index stands for the index of input order in Encoder
    • Decoder, high index stands for the index of generated items in Decoder

    stands for the parameter for generate the j-th item ()in Decoder with respect of the i-th input() in X.

  2. Variables

    • Encoder input, ,
    • Encoder shared parameter, A: RNN or LSMT shared parameter
    • Encoder output , output at each step of RNN or LSMT
    • Decoder initial input , denote also as
    • key,
    • query
    • Query Martix,
    • Encoder Weight ,
    • Eecoder Context Vector,
    • Decoder initial input , denote also as
    • Decoder output,
  3. update Network with softmax(c) get the prediciton, and corss enteopy update network back()

simple RNN + self attention

only Encoder, e Without Decoder and Decoder input, after RNN or LSTM we get Now unlike before only pass the last element to Decoder, we use attention skill to mix all input information

  1. Notion:

    • Encoder, lower index stands for the index of input order in Encoder
    • Generation, high index stands for the index of generated items

    stands for the parameter for generate the j-th item ()in Encoder with respect of the i-th input() in X.

  2. Variables

    • Encoder input, ,
    • Encoder shared parameter, A: RNN or LSMT shared parameter
    • Encoder output , output at each step of RNN or LSMT
    • key,
    • query
    • Query Martix,
    • Encoder Weight ,
    • Eecoder Context Vector,
  3. update Network

    • with softmax(c) get the prediciton, and corss enteopy update network back()
  4. Note

    • attention: key, with
    • self attention: key,

attention layer

An attention function can be described as mapping a query and a set of key-value pairs to an output Encoder Input E Decoder Input Removing RNN or LSMT, only constructing attention layer

  1. Notion:

    • Encoder, lower index stands for the index of input order in Encoder
    • Decoder, high index stands for the index of generated items in Decoder

    stands for the parameter for generate the j-th item ()in Decoder with respect of the i-th input() in X.

  2. Variables

    • value,
    • query
    • key,
    • Query Martix,
    • Encoder Weight ,
    • Eecoder Context Vector,
  3. update Network

    • with softmax(c) get the prediciton, and corss enteopy update network back()
  4. Note

    • X replace H, but still seq2seq model(with X')

self attention layer

only Encoder, e Without Decoder and Decoder input,

  1. Notion:

    • Encoder, lower index stands for the index of input order in Encoder
    • Generation, high index stands for the index of generated items

    stands for the parameter for generate the j-th item ()in Encoder with respect of the i-th input() in X.

  2. Variables

    • Encoder input, ,
    • value,
    • key,
    • query
    • Query Martix,
    • Encoder Weight ,
    • Eecoder Context Vector,
  3. update Network with softmax(c) get the prediciton, and corss enteopy update network back()

  4. Note

    • in query , it's X , not X'

transformer model

  /--+--\    /-----\    /-----\    /-----\   
  |a_1  |    |a_2  |    |a_3  |    |a_m  |  
  |     |    |     |    |     |    |     |
  \-----/    \-----/    \-----/    \-----/

+-------------------------------------------+
|cBLU                                       |
|Encoder                                    |
|    h1         h2         h3        hm     |
| +------+   +-----+    +-----+   +-----+   |
| |      |   |     |    |     |   |     |   |>------\
| | A    |   | A   |    | A   |   | A   |   |       |
| +--+---+   +--+--+    +--+--+   +---+-+   |       |
|    ^          ^          ^          ^     |       |
+----+----------+----------+----------+-----+       |
     |          |          |          |             |
  /--+--\    /-----\    /-----\    /-----\          |
  |X_1  |    |X_2  |    |X_3  |    |X_m  |          |
  |     |    |     |    |     |    |     |          |
  \-----/    \-----/    \-----/    \-----/          |
                                                    |        /--+--\    /-----\    /-----\    /-----\       
                                                    |        |c_1  |    |c_2  |    |c_3  |    |c_m  |  
                                                    |        |s_1  |    |s_2  |    |s_3  |    |s_m  |
                                                    |        \-----/    \-----/    \-----/    \-----/
                                                    |
                                                    |        +-------------------------------------------+
                                                    |        | c1AB                                      |
                                                    \------->| Decoder                                   |
                                                             | +------+   +-----+    +-----+   +-----+   |
                                                             | |      |   |     |    |     |   |     |   |
                                                             | | A'   |   | A'  |    | A'  |   | A'  |   |
                                                             | +--+---+   +--+--+    +--+--+   +---+-+   |
                                                             |    ^          ^          ^          ^     |
                                                             +----+----------+----------+----------+-----+
                                                                  |          |          |          |  
                                                               /--+--\    /-----\    /-----\    /-----\ 
                                                               |X'1  |    |X'2  |    |X'3  |    |X'm  |  
                                                               |     |    |     |    |     |    |     |
                                                               \-----/    \-----/    \-----/    \-----/

Bert

ViT


title: Informatik

#+STARTUP: overview

Schaltnetze

Gatter und Haskell

NOT AND OR NAND NOR

let can not as sentence use alone, but can be as a part in main

table_row :: ([Bool] -> Bool) -> [Bool] -> String
table_row f xs = show xs ++ " : " ++ show(f xs)

table :: ([Bool] -> Bool) -> [[Bool]] -> String
table f xs
  |xs == [] = ""
  |otherwise = table_row f (head xs) ++ " \n " ++ table f (tail xs)

main = do
  let boool_tri = [[ a,b,c ] | a <- [True, False, False],
                  b <- [False, True, False],
                  c <- [False, True, True]]

  putStrLn (table and boool_tri)


tableA :: ([Bool] -> Bool) -> [[Bool]] -> String
tableA f [] = ""
tableA f (x:xs) = table_row f x ++ " \n  "++ tableA f xs

Komplexitätstheorie

Landau Symbols

Master Theorem

description

In a Recursive process, we can form this, , for , . T 代表递归符号, a: 每次递归后重复的次数, n/b: 递归后每个部分的问题规模, f(n): 递归后将所有部分融合的步骤, 作如 下变换:

如果 在减去一个存在的 后仍然大于d, 则 :. 直接

如果 恒等于 d, 则: 直接用 乘以 .

注意: 此处是 中k=0的特列, 完整的表达是 if , with k>=0,

如果 在加上一个存在的 ϵ 后仍然小于d, 则 :. 直接f(n) 这种情况要检测正则性: if $ ∃ c < 1$ so that, . if not, Master Theorem can't be used in this case

1 example

a = 3,

b = 2,

so that,

Regularity condition:

, so , for example c = 4/5

so

2 example

a = 4

b = 2

3 example

a = 1, b = 2

Regularity condition: , , such

4 example

4

, b = 2,

5 example

a = 16, b = 4;

6 example

a = 2, b = 2

so that, is polynomial bigger than , or is polynomial smaller than O(f(n)),

But in the extend of second case: so

7 example

a = 2, b = 2,

so that, is polynomial bigger than , or is polynomial smaller than O(f(n)),

But in the extend of second case for k = -1:

8 example

a = 2, b = 4,

Regularity Condition: , that a(f(n/b)) < c f(n);

9 example

a = 1/2, b = 2,

10 example

a = 16, b = 4,

Regularity condition: , , so that af(n/b) < cf(n).

11 example

, b = 2,

12 example

a = 3, b = 2

13 example

a = 3, b = 3

14 example

a = 4, b =2,

15 example

a = 3, b = 4,

Regularity condition: if ∃ c < 1$, so that,af(n/b) < cf(n)

for , ;

so,

16 example

a = 3, b = 3,

17 example

a = 6, b = 3

Regularity condition: so that,

18 example

a = 4, b = 2,

19 example

a = 64, b = 8,

for extend second case, , for k = 1

so

20 example

a = 7, b = 3,

Regularity condition: , so that af(n/b) < cf(n), such as c = 8/9;

21 example

a = 4, b = 2,

22 example

a = 1, b = 2,

Regularity condition: if , for c <1. so that .

P & NP

def


P problem Es gibt ein Polynom p(n) und eine p(n)-Zeitbeschrankte DTM m mit L=L(m)} NP problem Es gibt ein Polynom p(n) und eine p(n)-Zeitbeschrankte NTM m mit L=L(m)} ExpTime problem Es gibt ein Polynom p(n) und eine 2^p^(n)-Zeitbeschrankte DTM m mit L=L(m)}


Rudction Many-one-Rudction : alle P Problem konnen auf one Problem reduzieren.

NP

SAT <- 3SAT <- 3 Farbarkeit <- Clique <- Independent Set <- Vertex Set Pa

computer vision

Ubungs 01

Solution erkälerung Mediuem under Quantil 25% ober Quantil 75%

Entopie

Anisotorpie

Paar-Grauwertmatrix

Hash

Gerneral

Verlastungsfaktor n : elementen m : Hash Blukets

For Kollision Offenes Hash : mit verkertete List Universumes Hash : mit ein hash famliy function Geschlossens Hash : die weiter hash bluket besiten verdoppelungsstrategie : verkleinen order vergrossen die Hash Blukets

Universal Hash

Definition

We want to save a dataset A localy into dataset B, with has m slots in B and fast access to search, insert, delete operation,

assiging A has n elements.

In oder to guarantee the elements from A will be randomly distributed in B to avoiding the unnecessary collision, we define our universal Hashing hat following property:

where x, y belongs to dataset A and , x < n, y < n,

m is the bins of mapped Dataset B,

h is the wanted universal hashing function instance, from Uninstall Hashing family H

one example of h can be Carter-Wegman hash function

Carter-Wegman hash function

Carter-Wegman hash function is :

::: center h(x) = [(ax+b)mod p] mod m :::

assiging p is the nearest prime number bigger than n,

and 0 < a, b < p,

proof: for , (ax+b)-(ay+b) = a(x-y) is not divisible by p ? why?? Is the following a theorem?

Theorem?

::: center Assigning $b$( in our case: x-y ) is an arbitrary intergel number, and is the a prime number and bigger than , there is not such (in our case is also denote as a ) exist, such than 0 < < , and is divisible by :::

If the upper rule holds, then because (ax+b)-(ay+b) = a(x-y) is not divisible by p,

so (ax+b) mod p (ay+b) mod p

for arbitrary anb ,

(ax+b)mod p and (ay+b) mod can have p possibilities and (p-1) possibilities.

so for arbitrary a and b, there are p(p-1) possibilities to locate in B dataset,

because p(p-1) is much more bigger than m, (normally m < n < p),

So we can guarantee that the distribution of elements in B can be very randomly and average.

Python example

this example is from zydeon github

from math import ceil, log2
from primesieve import nth_prime
from random import randint
import numpy as np

class UniversalHashing:
    """ N = #bins
        p = prime number st: p >= N """

    def __init__(self, N, p=None):
        self.N = N
        if p is None:
            p = nth_prime(1, 1 << max(32, ceil(log2(N))))
        assert p >= N, 'Prime number p should be at least N!'
        self.p = p

    def draw(self):
        a = randint(1, self.p - 1)
        b = randint(0, self.p - 1)
        return lambda x: ((a * x + b) % self.p) % self.N


if __name__ == '__main__':
    N = 50  # bins
    n = 100000  # elements
    H = UniversalHashing(N)
    h = H.draw()

    T = [0] * N
    for _ in range(n):
        x = randint(0, n * 10)
        T[h(x)] += 1

for i in range(len(T)):
    print(T[i] / n)    # This should be approximately equal

0.02026
0.02023
0.02001
0.02017
0.01979
0.01949
0.01999
0.01948
0.01958
0.02085
0.02027
0.02041
0.02056
0.02029
0.01867
0.01959
0.02041
0.02004
0.0198
0.02024
0.01969
0.02046
0.02036
0.01984
0.02044
0.02071
0.02033
0.01995
0.01955
0.02052
0.01984
0.01987
0.01958
0.01908
0.01956
0.01964
0.02007
0.02056
0.01997
0.02011
0.02023
0.02024
0.01996
0.01954
0.01988
0.02003
0.01998
0.02037
0.02009
0.01942

Here we can see all elements are randomly distributed in the mapped dataset,

and in upper code a, b and input dataset, all are randomly generated.

But the question is: this can't be reproduced, which means, if we hash the
same input again, we will get totally different hash distribution.
In practical applications, we have to remember the return index of hashtable,
otherwise we can't find it again in hashtable, even we never know if it still in the table.

universal hash with reproducible

So we want to overcome this problem with reproducible porperty. We fix the a and b, in our following assumpation we set a = b = p-1 applying the Carter-Wegman hash function for the given input data. if the return index is empty, we use it as our hash value.

if the index has been token, we reduce a and b by one, and apply Carter-Wegman hash function again to find a suitable index in hashtable.

over loop this process until one empty hashtable index is return

::: center Here in our reproducible universal hash, if the half hashtable has been token, we double the size of hashtable, so than the over loop process will not be too long. Because the Carter-Wegman hash function use the hashtable size m, so the after resize the hashtable, all elements will be computed again in new hashtable, this take an enormous effort. :::

  1. check the input data from 100000 to 100100

    from math import ceil, log2
    from primesieve import nth_prime
    from random import randint
    import numpy as np
    
    class UniversalHashing:
        """ N = #bins
            p = prime number st: p >= N """
    
        def __init__(self, N=200, p=None):
            self.N = N
            self.T = [0] * self.N
            if p is None:
                p = nth_prime(1, 1 << max(32, ceil(log2(N))))
            assert p >= N, 'Prime number p should be at least N!'
            self.p = p
            self.a = p - 1
            self.b = p - 1
    
        def draw(self):
            return lambda x: ((self.a * x + self.b) % self.p) % self.N
    
    def hash(x, H):
        H.a = H.p - 1
        H.b = H.p - 1
        while (H.T[H.draw()(x)] != 0):
            H.a -= 1
            H.b -= 1
        H.T[H.draw()(x)] = x
    
    def check(x, H):
        H.a = H.p - 1
        H.b = H.p - 1
        while(x != H.T[H.draw()(x)] and H.T[H.draw()(x)] != 0):
            H.a -= 1
            H.b -= 1
        if(x == H.T[H.draw()(x)]):
            print("x :{} is in hashtable".format(x))
            return 1
    
        if H.T[H.draw()(x)] == 0:
            print("x :{} is not in hashtable".format(x))
            return 0
    
    
    if __name__ == '__main__':
        H = UniversalHashing()
        Y = [i for i in range(100000, 100100, 1)]
        print(Y)
        for x in Y:
            hash(x, H)
    
        print(H.T)
    
        check(9000, H)
        check(100010, H)
    
    
    
    [100000, 100001, 100002, 100003, 100004, 100005, 100006, 100007, 100008, 100009, 100010, 100011, 100012, 100013, 100014, 100015, 100016, 100017, 100018, 100019, 100020, 100021, 100022, 100023, 100024, 100025, 100026, 100027, 100028, 100029, 100030, 100031, 100032, 100033, 100034, 100035, 100036, 100037, 100038, 100039, 100040, 100041, 100042, 100043, 100044, 100045, 100046, 100047, 100048, 100049, 100050, 100051, 100052, 100053, 100054, 100055, 100056, 100057, 100058, 100059, 100060, 100061, 100062, 100063, 100064, 100065, 100066, 100067, 100068, 100069, 100070, 100071, 100072, 100073, 100074, 100075, 100076, 100077, 100078, 100079, 100080, 100081, 100082, 100083, 100084, 100085, 100086, 100087, 100088, 100089, 100090, 100091, 100092, 100093, 100094, 100095, 100096, 100097, 100098, 100099]
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 100099, 100098, 100097, 100096, 100095, 100094, 100093, 100092, 100091, 100090, 100089, 100088, 100087, 100086, 100085, 100084, 100083, 100082, 100081, 100080, 100079, 100078, 100077, 100076, 100075, 100074, 100073, 100072, 100071, 100070, 100069, 100068, 100067, 100066, 100065, 100064, 100063, 100062, 100061, 100060, 100059, 100058, 100057, 100056, 100055, 100054, 100053, 100052, 100051, 100050, 100049, 100048, 100047, 100046, 100045, 100044, 100043, 100042, 100041, 100040, 100039, 100038, 100037, 100036, 100035, 100034, 100033, 100032, 100031, 100030, 100029, 100028, 100027, 100026, 100025, 100024, 100023, 100022, 100021, 100020, 100019, 100018, 100017, 100016, 100015, 100014, 100013, 100012, 100011, 100010, 100009, 100008, 100007, 100006, 100005, 100004, 100003, 100002, 100001, 100000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    x :9000 is not in hashtable
    x :100010 is in hashtable
    
  2. check randint from 1 to 10000

    from math import ceil, log2
    from primesieve import nth_prime
    from random import randint
    import numpy as np
    
    
    class UniversalHashing:
        """ N = #bins
            p = prime number st: p >= N """
    
        def __init__(self, N=200, p=None):
            self.N = N
            self.T = [0] * self.N
            if p is None:
                p = nth_prime(1, 1 << max(32, ceil(log2(N))))
            assert p >= N, 'Prime number p should be at least N!'
            self.p = p
            self.a = p - 1
            self.b = p - 1
    
        def draw(self):
            return lambda x: ((self.a * x + self.b) % self.p) % self.N
    
    
    def hash(x, H):
        H.a = H.p - 1
        H.b = H.p - 1
        while (H.T[H.draw()(x)] != 0):
            H.a -= 1
            H.b -= 1
        H.T[H.draw()(x)] = x
    
    
    def check(x, H):
        H.a = H.p - 1
        H.b = H.p - 1
        while(x != H.T[H.draw()(x)] and H.T[H.draw()(x)] != 0):
            H.a -= 1
            H.b -= 1
        if(x == H.T[H.draw()(x)]):
            print("x :{} is in hashtable".format(x))
            return 1
    
        if H.T[H.draw()(x)] == 0:
            print("x :{} is not in hashtable".format(x))
            return 0
    
    
    if __name__ == '__main__':
        H = UniversalHashing()
        Y = [randint(1, 10000) for _ in range(100)]
        print(Y)
        for x in Y:
            hash(x, H)
    
        print(H.T)
    
        check(9000, H)
        check(100010, H)
    
    
    
    [9499, 7809, 9665, 6560, 686, 9560, 6894, 1930, 972, 2659, 50, 8111, 4054, 1588, 9634, 2645, 1875, 6573, 4764, 1851, 3661, 6733, 86, 787, 1139, 1558, 6823, 3650, 2438, 7334, 9074, 3704, 493, 8574, 4280, 6603, 1136, 870, 7313, 7619, 3580, 9129, 1421, 9342, 3873, 9500, 8961, 1279, 3997, 9743, 2565, 8310, 207, 6131, 604, 1294, 9481, 8943, 5951, 8554, 4773, 198, 8479, 8771, 941, 834, 8605, 9254, 3543, 6344, 428, 9841, 3361, 7714, 9908, 2579, 8696, 202, 3235, 6120, 5263, 3912, 2815, 2625, 190, 8407, 4294, 2638, 9100, 7234, 2782, 7793, 9647, 1053, 651, 1309, 9606, 6526, 5017, 2505]
    [8310, 9254, 9908, 0, 0, 2505, 3704, 651, 0, 3650, 9500, 9499, 0, 0, 8696, 0, 6894, 493, 0, 0, 0, 0, 0, 8943, 686, 0, 4294, 0, 0, 9481, 4280, 1279, 0, 2638, 0, 1875, 9074, 3873, 0, 0, 870, 834, 0, 0, 0, 9665, 0, 5263, 0, 3661, 86, 2659, 0, 0, 0, 0, 4054, 1053, 0, 1851, 50, 0, 0, 9647, 0, 2645, 7234, 0, 0, 9841, 0, 8407, 2438, 0, 0, 3235, 9634, 0, 0, 3543, 0, 0, 428, 0, 0, 2625, 0, 6823, 0, 1421, 0, 7619, 0, 5017, 0, 2815, 0, 0, 0, 0, 0, 7809, 0, 207, 9606, 8605, 604, 6603, 202, 9100, 0, 0, 198, 3997, 0, 0, 0, 7793, 0, 0, 190, 1294, 1588, 787, 0, 0, 0, 0, 2782, 0, 3580, 2579, 0, 0, 0, 0, 8574, 6573, 972, 8771, 0, 0, 0, 0, 0, 2565, 4764, 0, 0, 8961, 6560, 8479, 1558, 0, 0, 0, 8554, 0, 0, 5951, 0, 1309, 0, 4773, 0, 0, 6344, 9743, 9342, 941, 0, 1139, 0, 0, 1136, 0, 7334, 6733, 0, 6131, 1930, 9129, 0, 0, 6526, 0, 0, 3361, 0, 9560, 6120, 0, 0, 0, 0, 0, 7714, 7313, 3912, 8111]
    x :9000 is not in hashtable
    x :100010 is not in hashtable
    
  3. check 100 special input data

    we use

    Y = [H.N*randint(1, 100) for _ in range(100)]
    

    to generate 100 collision data, we can see all data collided into the same slot if we just use fixed a, b (seeing upper) without a -= 1 and b -= 1. and with the reduction, all special data are average distributed.

    from math import ceil, log2
    from primesieve import nth_prime
    from random import randint
    import numpy as np
    
    class UniversalHashing:
        """ N = #bins
            p = prime number st: p >= N """
    
        def __init__(self, N, p=None):
            self.N = N
            if p is None:
                p = nth_prime(1, 1 << max(32, ceil(log2(N))))
            assert p >= N, 'Prime number p should be at least N!'
            self.p = p
    
        def draw(self):
            a = self.p - 1
            b = self.p - 1
            # a = randint(1, self.p - 1)
            # b = randint(0, self.p - 1)
            return lambda x: ((a * x + b) % self.p) % self.N
    
    if __name__ == '__main__':
        N = 50  # bins
        n = 100000  # elements
        H = UniversalHashing(N)
        h = H.draw()
    
        T = [0] * N
    
        # for _ in range(n):
        #     x = randint(0, n * 10)
        #     T[h(x)] += 1
    
        Y = [H.N*randint(1, 100) for _ in range(100000)]
        for x in Y:
            T[h(x)] += 1
    
    
    for i in range(len(T)):
        print(T[i] / n)    # This should be approximately equal
    
    
    0.0
    0.0
    0.0
    0.0
    0.0
    0.0
    0.0
    0.0
    0.0
    0.0
    1.0
    0.0
    0.0
    0.0
    0.0
    0.0
    0.0
    0.0
    0.0
    0.0
    0.0
    0.0
    0.0
    0.0
    0.0
    0.0
    0.0
    0.0
    0.0
    0.0
    0.0
    0.0
    0.0
    0.0
    0.0
    0.0
    0.0
    0.0
    0.0
    0.0
    0.0
    0.0
    0.0
    0.0
    0.0
    0.0
    0.0
    0.0
    0.0
    0.0
    
    from math import ceil, log2
    from primesieve import nth_prime
    from random import randint
    import numpy as np
    
    
    class UniversalHashing:
        """ N = #bins
            p = prime number st: p >= N """
    
        def __init__(self, N=200, p=None):
            self.N = N
            self.T = [0] * self.N
            if p is None:
                p = nth_prime(1, 1 << max(32, ceil(log2(N))))
            assert p >= N, 'Prime number p should be at least N!'
            self.p = p
            self.a = p - 1
            self.b = p - 1
    
        def draw(self):
            return lambda x: ((self.a * x + self.b) % self.p) % self.N
    
    
    def hash(x, H):
        H.a = H.p - 1
        H.b = H.p - 1
        while (H.T[H.draw()(x)] != 0):
            H.a -= 1
            H.b -= 1
        H.T[H.draw()(x)] = x
    
    
    def check(x, H):
        H.a = H.p - 1
        H.b = H.p - 1
        while(x != H.T[H.draw()(x)] and H.T[H.draw()(x)] != 0):
            H.a -= 1
            H.b -= 1
        if(x == H.T[H.draw()(x)]):
            print("x :{} is in hashtable".format(x))
            return 1
    
        if H.T[H.draw()(x)] == 0:
            print("x :{} is not in hashtable".format(x))
            return 0
    
    
    if __name__ == '__main__':
        H = UniversalHashing()
        Y = [H.N*randint(1, 100) for _ in range(100)]
    
        print(Y)
        for x in Y:
            hash(x, H)
    
        print(H.T)
    
        check(9000, H)
        check(100010, H)
    
    
    
    [14800, 10600, 1400, 4800, 3400, 17800, 12400, 19800, 10200, 9600, 15800, 5200, 8800, 15200, 18200, 1000, 6200, 6800, 16400, 1800, 8800, 12600, 12600, 9600, 16800, 12800, 14400, 3400, 5800, 11600, 19600, 5600, 5400, 9800, 2000, 7800, 15000, 1800, 18800, 16800, 17600, 9000, 18600, 11800, 19200, 16800, 200, 18800, 19200, 6400, 3000, 12000, 2800, 13600, 13600, 16400, 2000, 16400, 19200, 9200, 6200, 11600, 14800, 18200, 17000, 1200, 17800, 12000, 13200, 17200, 9600, 16200, 8200, 15200, 12000, 8400, 15600, 1800, 4000, 1600, 8200, 16000, 9200, 1400, 14000, 1400, 17000, 3200, 2200, 14800, 14200, 11000, 3600, 14200, 8600, 13000, 7400, 7200, 10600, 17600]
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 17600, 10600, 7200, 7400, 13000, 8600, 14200, 3600, 11000, 14200, 14800, 2200, 3200, 17000, 1400, 14000, 1400, 9200, 16000, 8200, 1600, 4000, 1800, 15600, 8400, 12000, 15200, 8200, 16200, 9600, 17200, 13200, 12000, 17800, 1200, 17000, 18200, 14800, 11600, 6200, 9200, 19200, 16400, 2000, 16400, 13600, 13600, 2800, 12000, 3000, 6400, 19200, 18800, 200, 16800, 19200, 11800, 18600, 9000, 17600, 16800, 18800, 1800, 15000, 7800, 2000, 9800, 5400, 5600, 19600, 11600, 5800, 3400, 14400, 12800, 16800, 9600, 12600, 12600, 8800, 1800, 16400, 6800, 6200, 1000, 18200, 15200, 8800, 5200, 15800, 9600, 10200, 19800, 12400, 17800, 3400, 4800, 1400, 10600, 14800, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    x :9000 is in hashtable
    x :100010 is not in hashtable
    
  4. search key

    we also used the check function to check if the data is already in hashtable, the check can be done for with and without collision input data. we use 100, 200, 300,... to 20000 as input, so we can check some of it, such as 5000, 9000 5000, or 9000 is in the hashtable even they collided many times.

    from math import ceil, log2
    from primesieve import nth_prime
    from random import randint
    import numpy as np
    
    class UniversalHashing:
        """ N = #bins
            p = prime number st: p >= N """
    
        def __init__(self, N=200, p=None):
            self.N = N
            self.T = [0] * self.N
            if p is None:
                p = nth_prime(1, 1 << max(32, ceil(log2(N))))
            assert p >= N, 'Prime number p should be at least N!'
            self.p = p
            self.a = p - 1
            self.b = p - 1
    
        def draw(self):
            return lambda x: ((self.a * x + self.b) % self.p) % self.N
    
    
    def hash(x, H):
        H.a = H.p - 1
        H.b = H.p - 1
        while (H.T[H.draw()(x)] != 0):
            H.a -= 1
            H.b -= 1
        H.T[H.draw()(x)] = x
    
    
    def check(x, H):
        H.a = H.p - 1
        H.b = H.p - 1
        while(x != H.T[H.draw()(x)] and H.T[H.draw()(x)] != 0):
            H.a -= 1
            H.b -= 1
        if(x == H.T[H.draw()(x)]):
            print("x :{} is in hashtable".format(x))
            return 1
    
        if H.T[H.draw()(x)] == 0:
            print("x :{} is not in hashtable".format(x))
            return 0
    
    
    if __name__ == '__main__':
        H = UniversalHashing()
        Y = [H.N*i for i in range(100)]
    
        print(Y)
        for x in Y:
            hash(x, H)
    
        print(H.T)
    
        check(5000, H)
        check(9000, H)
        check(10300, H)
    
    
    
    [0, 200, 400, 600, 800, 1000, 1200, 1400, 1600, 1800, 2000, 2200, 2400, 2600, 2800, 3000, 3200, 3400, 3600, 3800, 4000, 4200, 4400, 4600, 4800, 5000, 5200, 5400, 5600, 5800, 6000, 6200, 6400, 6600, 6800, 7000, 7200, 7400, 7600, 7800, 8000, 8200, 8400, 8600, 8800, 9000, 9200, 9400, 9600, 9800, 10000, 10200, 10400, 10600, 10800, 11000, 11200, 11400, 11600, 11800, 12000, 12200, 12400, 12600, 12800, 13000, 13200, 13400, 13600, 13800, 14000, 14200, 14400, 14600, 14800, 15000, 15200, 15400, 15600, 15800, 16000, 16200, 16400, 16600, 16800, 17000, 17200, 17400, 17600, 17800, 18000, 18200, 18400, 18600, 18800, 19000, 19200, 19400, 19600, 19800]
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 19800, 19600, 19400, 19200, 19000, 18800, 18600, 18400, 18200, 18000, 17800, 17600, 17400, 17200, 17000, 16800, 16600, 16400, 16200, 16000, 15800, 15600, 15400, 15200, 15000, 14800, 14600, 14400, 14200, 14000, 13800, 13600, 13400, 13200, 13000, 12800, 12600, 12400, 12200, 12000, 11800, 11600, 11400, 11200, 11000, 10800, 10600, 10400, 10200, 10000, 9800, 9600, 9400, 9200, 9000, 8800, 8600, 8400, 8200, 8000, 7800, 7600, 7400, 7200, 7000, 6800, 6600, 6400, 6200, 6000, 5800, 5600, 5400, 5200, 5000, 4800, 4600, 4400, 4200, 4000, 3800, 3600, 3400, 3200, 3000, 2800, 2600, 2400, 2200, 2000, 1800, 1600, 1400, 1200, 1000, 800, 600, 400, 200, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    x :5000 is in hashtable
    x :9000 is in hashtable
    x :10300 is not in hashtable
    

Tree Theorem

Vorgänger(u)

if least(root) = u no Vorgänger


if u.L exits greatest(u.L) if u.L not exits u is right child father node if u.L not exits u is left child (grand)father which has right child

Nachfolger(v)

if greatest(root) = v no Nachfolger


if v.R exits least(u.L) if v.R not exits v is left child father node if v.R not exits v is right child (grand)father which has left child

Quantum Computation


title: Linux

#+startup: content

Install

ISO installation


lsblk list all partiation mkfs format partiation fdisk manage partiation


lsblk
sudo umount....
format the partation: 
sudo mkfs -t ext4 /dev/sda1
sudo mkfs -t ext4 /dev/sda2
sudo mkfs -t ext4 /dev/sda
sudo dd if=.../ubuntu-20.04.3-desktop-amd64.iso of=/dev/sda bs=4M status=progress && sync
resize the host
....
sudo mkfs -t ext4 /dev/sda
sudo fdisk -l
sudo fdisk  /dev/sda -> m, g, n, 1, Enter, w

sudo dd if=/dev/nvm..p1 of=/dev/sda1
sudo dd if=/dev/nvm..p3 of=/dev/sda2


from windows: Rufus
Disk can delete all partation in linux 
lsblk -f
sudo mkfs -t ext4 /dev/sda
from Linux:
sudo dd if=~/Downloads/ubuntu-20.04.3-desktop-amd64.iso of=/dev/sda bs=4M status=progress && sync

backup system

one step to backup in USB

sudo dd if=/dev/nvmxx2 of=/dev/sda2 bs=4M status=progress && sync  

old setting insert SSD usb $ lsblk

check the partition of whole disk

$ sudo fdisk -l

check the detail partation

$ sudo mkfs -t ext4 /dev/sda

format sda  disk (can also for partition )

$ sudo fdisk /dev/sda

make new partiation distribation for backup

$ sudo dd if=/dev/nvmxx2 of=/dev/sda2 bs=4M status=progress && sync

backup the whole system disk into sda2 backup partition

$ disk resize the restore partation

this step can open the Disks in APP, and resize the system disk,
better if the system disk is 10GB bigger than the backup partition.
Later for backup again, don't forget resize it back to backup again

$ sudo mkfs -t ext4 /dev/nvmxxx2

clean the system partition

$ sudo dd if=/dev/sda2 of=/dev/nvmxx2 bs=4M status=progress && sync

should be just fine

grub repair

for error : Minimal BASH-like line editing is supported......

grub > ls 
grub > ls (hd0,gptXX)/boot/grub

if XX partation returns many file, one is with grub.cfg, this is the one we want

grub > set root=(hd0,gptXX)
grub > set prefix=(hd0,gptXX)/boot/grub
grub > normal

enter the system

sudo add-apt-repository ppa:yannubuntu/boot-repair
sudo apt-get update
sudo apt-get install boot-repair
sudo grub-install /dev/where EFI partation is

Recover the fastplatte in windows

1. WIN+R diskpart
2. select disk (Disk)
3. clean
4. new add 

write images in USB

  1. 下载ubuntu
  2. 下载USBwriter并安装
  3. 写入系

reboot

my computer : F12

Update nvidia drivers for linux

sudo add-apt-repository ppa:graphics-drivers/ppa
sudo apt update 
ubuntu-drivers devices
sudo apt-get --reinstall install nvidia-430
    1.  will be asked for password
    2.  reboot
    3.  select Enroll MOK -> continue -> Yes -> Roboot
nvidia-sim
watch -n 1 nvidia-smi

chinese

export LC~CTYPE~=zh~CN~.UTF-8 sudo apt-get -y install language-pack-zh-hans 此应用压制中英文的同步变化, 尽量避免使用中文

Time Screensaver

NowSat Nov 5 12:29:50 2022, I just configured my computer for a time screensaver.

  • link

  • go the the link, for me only work with building from source, don't forget the dependence.

  • after install it add following into ~/.xscreensaver under section of programs:

    gluqlo -root \n\
    
  • install Xscreensaver if not with following, but before that, delete gnome-screensaver if exist.

    sudo apt-get install xscreensaver xscreensaver-data-extra xscreensaver-gl-extra
    
  • start Screensaver application, find the Gluqlo, and set it to be the only one, more setting is option

  • start startup application, add one as following, name and comment is as well(liberty)command is this: xscreensaver -nosplash

  • lauch keyshort, add keyshort as following, key combination is as personal wish

    xscreensaver-command -lock
    
  • change Wayland to xorg

    • sudo apt install xorg
    • sudo nano /etc/gdm3/custom.conf
    • WaylandEnable=false
  • now test the keyshort

System configuration collection

check port of application

ps -aux |grep mongo
netstat -nap |grep 80

open fire wall for port

sudo apt install firewalld add port : sudo firewall-cmd --add-port=80/tcp --permanent sudo firewall-cmd --remove-port=80/tcp --permanent restart firewall: sudo firewall-cmd --reload check port: sudo firewall-cmd --list-all

firewall

systemctl status firewalld systemctl stop firewalld systemctl disable firewalld systemctl enable firewalld

Shutdown Keyboard default

1. <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8889em;vertical-align:-0.1944em;"></span><span class="mord mathnormal">x</span><span class="mord mathnormal">in</span><span class="mord mathnormal">p</span><span class="mord mathnormal">u</span><span class="mord mathnormal" style="margin-right:0.01968em;">tl</span><span class="mord mathnormal">i</span><span class="mord mathnormal">s</span><span class="mord mathnormal" style="margin-right:0.13889em;">tF</span><span class="mord mathnormal">in</span><span class="mord mathnormal">d</span><span class="mord mathnormal">t</span><span class="mord mathnormal">h</span><span class="mord mathnormal">e</span><span class="mord mathnormal" style="margin-right:0.13889em;">T</span><span class="mord mathnormal">o</span><span class="mord mathnormal">u</span><span class="mord mathnormal">c</span><span class="mord mathnormal">h</span><span class="mord mathnormal">p</span><span class="mord mathnormal">a</span><span class="mord mathnormal">d</span><span class="mord mathnormal">an</span><span class="mord mathnormal">d</span><span class="mord mathnormal">i</span><span class="mord mathnormal">t</span><span class="mord mathnormal">s</span><span class="mord mathnormal" style="margin-right:0.10903em;">N</span><span class="mord mathnormal">A</span><span class="mord mathnormal" style="margin-right:0.05764em;">ME</span><span class="mord mathnormal">an</span><span class="mord mathnormal">d</span><span class="mord mathnormal" style="margin-right:0.07847em;">I</span><span class="mord mathnormal" style="margin-right:0.02778em;">D</span><span class="mord">2.</span></span></span></span> xinput set-prop 'NAME' 'Device Enabled' 0
   to close the Touchpad
3. but with following can be named as tpOn and tpOff in ./bashrc
alias tpOff="xinput set-prop 'SYNA1D31:00 06CB:CD48 Touchpad' 'Device Enabled' 0"
alias tpOn="xinput set-prop 'SYNA1D31:00 06CB:CD48 Touchpad' 'Device Enabled' 1"
4. Close Touchpad default in boost system
   the following in ~/.config/autostart/xinput.desktop

[Desktop Entry]
Type=Application
Exec=xinput set-prop 'SYNA1D31:00 06CB:CD48 Touchpad' 'Device Enabled' 0
Hidden=false
NoDisplay=false
X-GNOME-Autostart-enabled=true
Name[zh_CN]=touchpad enable
Name=touchpad enable

autostart

Thunderbird

[Desktop Entry]
Type=Application
Exec=/usr/bin/thunderbird
Hidden=false
NoDisplay=false
X-GNOME-Autostart-enabled=true
Name[en_US]=thunderbird
Name=thunderbird
Comment[en_US]=thunderbird
Comment=thunderbird

exchange Control Key and Caps Key

在/etc/default/keyboard文件中添加:

XKBOPTIONS="ctrl:nocaps

or

setxkbmap -option ctrl:nocaps

setting for 右键没反应 $ sudo add-apt-repository universe $ sudo apt install gnome-tweak-tool

right key no response

gsettings set org.gnome.desktop.peripherals.touchpad click-method areas

hotkey


C-M- t terminal C-M- p thunderbird C-M- e emacs C-M- f firefox C-M- j emacs windows switch C-M- t terminal C-M- w emacs worterbuch C-M- t terminal C-M- t terminal



Switch application Alt + Tab Switch window of an application Alt + Spc



Alt Ctrl Del 退出用户


in Einstellung, the executable command can be used in command for customized hotkey

clear caches

this command has been added to the .bashrc of the /root. only root user can call this command

alias freemem="sync; echo 3 > /proc/sys/vm/drop_caches && swapoff -a && swapon -a && printf '\n%s\n' 'Ram-cache and Swap Cleared' "

create customized dock to favorites

  • find the executable files and icon

  • create the desktop setting file: /usr/share/applications/myapp.desktop

  • change the settings and make it executable +x

  • new works as normal

    #!/usr/bin/env xdg-open
    [Desktop Entry]
    Version=1.0
    Type=Application
    Terminal=false
    Exec=/path/to/yourapp
    Name=YourApp
    Comment=Description of YourApp
    Icon=/path/to/yourapp.png
    

hstr

add-apt-repository ppa:ultradvorka/ppa
apt-get update
apt-get install hstr

the hh

commands

hits

  • assigne permition for delete
chmod -R u+rwx /usr/users/szhao/go-workspace/pkg/mod
  • /ect/ssh/sshd~config~
    • AllowedUsers cloud silin, allow such user login remotely

terminal

S-C-c : can copy out from terminal S-C-v : can paste into terminal C-h : backwards to delete C-j : enter C-k : cut after C-u : cut before

sammary

fdisk -l

fdisk /dev/nvme0n1p4 (m, p, n, ...)
mkfs.ext4 /dev/nvme0n1p4
sudo emacs /etc/fstab
/dev/nvme0n1p4 /home/silin/4GB ext4 defaults 0 0

in /etc/fstab, the command must be correct, otherwise the system can't booted.

cat < source1.c >> source2.c (add source1.c to the end of source2.c)

echo $PATH | tr \: \\n{=latex}

file management

在~内找filename的文件 find ~ -name filename

找到.bash~history内带有~"install"的内容 grep -n "install" .bash~history~

copy 110.txt to 111.txt echo | cat 110.txt > 111.txt

> 擦除再写 >> 追加写入

读取.sdsv~history的不重复内容~,再写入到.sdsv echo | sort -n .sdsv~history~ |uniq > .sdsv

directory operation

tree -L 2
alias open='nautilus'
open .

find uninstall and remove software

sudo apt list --installed | grep software
whereis software
sudo apt-get --purge remove software
sudo apt-get autoremove

su password config

sudo passwd :to configure the password of root user

get IP address

curl ifconfig.me

grep sort

grep -n "xxx" ./test.txt sort (--reverse -t " " -k 3 ) test.csv

softlink

ln -s filename linkname // 快捷方式
ln -s sourcefile softlinkname
filename加上绝对路径,linkname被移动后,仍能访问访问文件

hard link

ln filename linkname   //硬链接
不占用磁盘空间,重复连接到文件的inode点。
可以在不同地方通过硬连接对文件进行操作

cd to program with which

cd $(dirname $(which cling))

awk

delete the repeat : awk '!a[$0]++' file.txt

less


J down K up Space next page b previous page / search n next mark N previous mark q quit


静态库的制作

  1. 库方

    include/head.h lib/ src/ 将在src/中编写要实现的文件 并编译这些文件 $ gcc *.c -c -I ../include/ -I :链接头文件 再将这些编译后的打包 $ ar rcs libtest.a *.o ar : -archive 打包 检测 : nm libtest.a 前缀lib 和后缀.a 不能更改,实际名字是test

    最后将生成的libtest.a放到上级目录lib中, 可以将lib和include目录发送给甲方

  2. 甲方

    根据include/head.h 的头文件编写自己的应用文件main.c 编译main.c并链接头文件和库 $ gcc main.c -I ./include/ -L ./lib/ -ltest -o app -I : 连接头文件 -L : 链接库 -ltest : 链接库文件,去头lib 去尾.a -o: 指点生成的应用名

  3. 特点

    优点: 加载块,移植方便 缺点 :部署更新麻烦,引用的重复文件重复储存,浪费空间

动态库的制作

编译 $ gcc *.c -c -fpic -I ../include -fpic 或者 fPIC : 特殊命令 打包 $ gcc -shared *.o -o libxxx.so 头lib 尾.so

使用和静态库相似, 根据头文件编写应用文件main.c $ gcc main.c -I ./inculde/ -L ./lib/ -lxxx -o app

对于linux生成的文件都是elf格式,并由ld-libc.so动态加载,需要让app能别找 到可以用环境变量或者配置文件

  1. 环境变量

    临时设置 $ export LD~LIBRARYPATH~=./lib 或者新增 $ export LD~LIBRARYPATH~=./lib:LD~LIBRARYPATH~

    临时设置可以使用相对路径,

    永久设置 用户 $ cat " LD~LIBRARYPATH~=./lib:LD~LIBRARYPATH~" >> ~/.bashrc $ source ~./bashrc

    永久设置 系统 $ sudo cat "LD~LIBRARYPATH~=./lib:LD~LIBRARYPATH~" >> /etc/profile $ source /etc/profile

  2. 修改配置文件

    配置文件/etc/ld.so.conf $ sudo cat "绝对路径/lib" >> /etc/ld.so.conf $ sudo ldconfig -v 激活配置

  3. 通过函数加载

    dlopen dlclose dlsym

sshpass login

ssh user@ip sshpass -p password ssh user@ip

Login without password

ssh-keygen -r rsa and drei mal enter ssh-copy-id cloud@ip ssh-copy-id localhost(warming:username should not be hostname)

ssh root login

emacs /etc/ssh/sshd~config~

  1. PermitRootLogin yes
  2. AllowUsers root OtherUser

output redirect

comands xxx >> output file comands xxx &>> str error file

recursive string replace

find . -type f -name "*.md" -exec sed -i 's/foo/bar/g' {} +
find . -type f -name "*.vue" -exec sed -i 's/store.state.Timer/store.state.Session01/g' {} +

Useful Software

tar

-x : extract -c: compose -v: show the process -z: with zip -f : such file

tar -zvcf xxx.tar.gz xxx
tar -zvxf xxx.tar.gz

fcitx for sougou

1. sudo apt install fcitx
download sougou
2. sudo apt  --fix-broken install(after download)
3. export LC_CTYPE=zh_CN.UTF-8 (for Emacs)

eog

eog xxx.png to view png with bluit in software eog

Okular

sudo apt-get install okular
F2 to constimizer
F7 mode view
C-gg to the page
C-n page down
C-p page up
M-n scroll down
M-p scroll up
C-b C-b add Annoation, 1 to note
SPC-b add bookmark
SPC-SPC rename bookmark
SPC-n bookmark down
SPC-p bookmark up

xournal

sudo apt install xournal

evince

evince xxx.pdf to view pdf file

stardict

download dictionaries from, http://download.huzheng.org/ and http://download.huzheng.org/zh_TW/ extract, and put them in usr/share/stardict/dic , if without this folder, create it with root

sudo apt install stardict
sudo apt install sdcv 
cd ~/Dropbox/cs/Tools
bzip2 -dk *.bz2
for i in *.tar.bz2; do sudo tar -xjvf "$i" -C /usr/share/stardict/dic ; done

kmplayer

sudo apt install kmplayer

simplescreenrecorder

sudo apt install simplescreenrecorder
alias ssr='simplescreenrecorder'
 ssr
Ctrl + Shift + Alt + V start or pause 

Cvim

C-j moive to left 
C-k moive to right

hotopea

登陆photopea网站后,新建并上传图片 设置白色背景:图像 -> 调整 -> 色阶 点击下面的白色 后点击要处理的图片区域 去背景 : 魔术棒 , 点击去连续, 再直接delete

manual png create png

after edit a file.dot

dot -Tpng -O file.dot

gpg for secret

gpg --list-secret-keys
gpg -r user -e xxx.file
gpg -d xxx.file.gpg
after change xxx.file :gpg --verify xxx.file.gpg

ranger

apt install

pdftk

official web link


合并 pdftk 1.pdf 2.pdf 3.pdf output 123.pdf 多个不同页面合并 pdftk A=1.pdf B=2.pdf C=pdf cat A1-2 B2-3 C3 output abc.pdf 旋转第一页 pdftk in.pdf cat 1E 2-end output out.pdf 加密(128位) pdftk a.pdf output b.pdf owner~pw~ pass 加访问密码 pdftk a.pdf output b.pdf user~pw~ pass 解密 pdftk a.pdf input~pw~ pass output b.pdf 解压 pdftk a.pdf output b.pdf uncompress 压缩 pdftk a.pdf output b.pdf compress 修复 pdftk a.pdf output b.pdf 切割 pdftk a.pdf cat 1-end output b.pdf 分解成单页 pdftk a.pdf burst


Linux connect to Android

kedconnect on linux
kedconnect on android
with  the same internet connection can be found each other, and communication

The file can be found in Download folder of each devices

gs

remove active content from pdf

gs -dNOPAUSE -sDEVICE=pdfwrite -sOUTPUTFILE=CV.pdf -dBATCH CV.pdf

compress

gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/prepress -dNOPAUSE -dQUIET -dBATCH -sOutputFile=compressed~PDFfile~.pdf input~PDFfile~.pdf

mpv player

sudo apt install mpv

mpv.conf

no-osd-bar # 去掉白色进度条
save-position-on-quit # 关闭时记住文件播放位置
no-border # 去掉边框

# 解码-字幕
vo=opengl:gamma-auto:icc-profile-auto
hwdec=auto
autofit-larger=92%
playcache=8192
lang=zh,chi
video-sync=display-resample

sub-codepage=enca:zh:utf8
sub-auto=fuzzy
sub-text-font-size=40
sub-text-shadow-offset=0
sub-text-color="#ffffffff"
sub-text-font="STZhongsong"
sub-codepage=utf8:gb18030

screenshot-template=mpv-screenshot-%f-%p
screenshot-format=png

osd-font="STZhongsong"
osd-font-size=36

--script=/Users/yourname/.config/mpv/autoload.lua

autoload.lua

-- This script automatically loads playlist entries before and after the
-- the currently played file. It does so by scanning the directory a file is
-- located in when starting playback. It sorts the directory entries
-- alphabetically, and adds entries before and after the current file to
-- the internal playlist. (It stops if the it would add an already existing
-- playlist entry at the same position - this makes it "stable".)
-- Add at most 5000 * 2 files when starting a file (before + after).
MAXENTRIES = 5000

function Set (t)
    local set = {}
    for _, v in pairs(t) do set[v] = true end
    return set
end

EXTENSIONS = Set {
    'mkv', 'avi', 'mp4', 'ogv', 'webm', 'rmvb', 'flv', 'wmv', 'mpeg', 'mpg', 'm4v', '3gp',
    'mp3', 'wav', 'ogv', 'flac', 'm4a', 'wma',
}

mputils = require 'mp.utils'

function add_files_at(index, files)
    index = index - 1
    local oldcount = mp.get_property_number("playlist-count", 1)
    for i = 1, #files do
        mp.commandv("loadfile", files[i], "append")
        mp.commandv("playlist-move", oldcount + i - 1, index + i - 1)
    end
end

function get_extension(path)
    match = string.match(path, "%.([^%.]+)" )
    if match == nil then
        return "nomatch"
    else
        return match
    end
end

table.filter = function(t, iter)
    for i = #t, 1, -1 do
        if not iter(t[i]) then
            table.remove(t, i)
        end
    end
end

function find_and_add_entries()
    local path = mp.get_property("path", "")
    local dir, filename = mputils.split_path(path)
    if #dir == 0 then
        return
    end
    local pl_count = mp.get_property_number("playlist-count", 1)
    if (pl_count > 1 and autoload == nil) or
       (pl_count == 1 and EXTENSIONS[string.lower(get_extension(filename))] == nil) then
        return
    else
        autoload = true
    end

    local files = mputils.readdir(dir, "files")
    if files == nil then
        return
    end
    table.filter(files, function (v, k)
        local ext = get_extension(v)
        if ext == nil then
            return false
        end
        return EXTENSIONS[string.lower(ext)]
    end)
    table.sort(files, function (a, b)
        local len = string.len(a) - string.len(b)
        if len ~= 0 then -- case for ordering filename ending with such as X.Y.Z
            local ext = string.len(get_extension(a)) + 1
            return string.sub(a, 1, -ext) < string.sub(b, 1, -ext)
        end
        return string.lower(a) < string.lower(b)
    end)

    if dir == "." then
        dir = ""
    end

    local pl = mp.get_property_native("playlist", {})
    local pl_current = mp.get_property_number("playlist-pos", 0) + 1
    -- Find the current pl entry (dir+"/"+filename) in the sorted dir list
    local current
    for i = 1, #files do
        if files[i] == filename then
            current = i
            break
        end
    end
    if current == nil then
        return
    end

    local append = {[-1] = {}, [1] = {}}
    for direction = -1, 1, 2 do -- 2 iterations, with direction = -1 and +1
        for i = 1, MAXENTRIES do
            local file = files[current + i * direction]
            local pl_e = pl[pl_current + i * direction]
            if file == nil or file[1] == "." then
                break
            end

            local filepath = dir .. file
            if pl_e then
                -- If there's a playlist entry, and it's the same file, stop.
                if pl_e.filename == filepath then
                    break
                end
            end

            if direction == -1 then
                if pl_current == 1 then -- never add additional entries in the middle
                    mp.msg.info("Prepending " .. file)
                    table.insert(append[-1], 1, filepath)
                end
            else
                mp.msg.info("Adding " .. file)
                table.insert(append[1], filepath)
            end
        end
    end

    add_files_at(pl_current + 1, append[1])
    add_files_at(pl_current, append[-1])
end

mp.register_event("start-file", find_and_add_entries)

mellplayer

sudo apt-get install libmpv-dev mpv

thunderbird

Alt to open the menubar,
Ansicht Anpassen to setting ungelesen

For Filter:
cd ~/.thunderbird/4r373mm9.default-release/ImapMail/imap.gmail.com
import msgFilterRules.dat to Gmail

EverSync

Eversync sync all bookmarks between chrome and firefox with G Konten

IPFS

download go-ipfs and untar
cp ipfs /usr/local/bin and sudo ./install.sh

sudo apt install ipfs

ipfs init
export EDITOR=/usr/bin/emacs
ipfs config edit
ipfs id
ipfs  help


mkdir IPFS
echo "balabalu" > hallo.org
ipfs add hallo.org  :get file_hash
ipfs cat file_hash
ipfs.io/ipfs/file_hash

push

ipfs add -r . (we get all file_hash(s), and a folder_hash(IPFS))
ipfs name publish folder_hash  (: to IDHASH)

in Webborser: ipfs.io/ipns/IDHASH


ipfs name resolve IDHASH : to HASH_file

特殊加密,暂时不用
ipfs key gen --type=rsa --size=2048 IPFS
ipfs name publish --key=IPFS folder_hash

ipfs config --json API.HTTPHeaders.Access-Control-Allow-Methods '["PUT", "GET", "POST","OPTIONS"]'

ipfs config --json API.HTTPHeaders.Access-Control-Allow-Origin '["*"]'

ipfs config --json API.HTTPHeaders.Access-Control-Allow-Credentials '["true"]'

ipfs config --json API.HTTPHeaders.Access-Control-Allow-Headers '["Authorization"]'

ipfs config --json API.HTTPHeaders.Access-Control-Expose-Headers '["Location"]'


http://localhost:5001/webui


ipfs files mkdir /Docu

ipfs files ls /Docu

ipfs file cp /ipfs/HASH

GPG


terminal encrypt gpg --recipient ID --output en.org --encrypt source.org terminal decrypt gpg en.org emacs encrypt epa-encrypt-file emacs decrypt epa-decrypt-file


encrypt by terminal, once decrypt by emacs, just as normal file, can be edited anytime encrypt by emacs with password, passwd will be ask every time by after edit if epa-file-select-key is t

Zulip Rocket Chat

System control

system backup

mount rsync

查看系统的磁盘 :lsblk 再将磁盘(也可以是某个分区)挂载到某个点 :

该磁盘可以是正在使用的磁盘或者分区

 mount /dev/disk /media/Linux
sudo mount /dev/sda1 /media/Backup

rsync -aAXv --delete --exclude=media target backup/LinuxBackUp20200316
my opera 

rsync -aAXv /home/sx/ /media/sx/A672BA1B72B9EFE3/linuxbackup/home/

如果要恢复,重复上面的过程,再将target backup 交换

system performance

  1. systemlastanzeigen sudo apt install indicator-multiload

  2. dependence

sudo apt-get install gir1.2-gtop-2.0 gir1.2-networkmanager-1.0 gir1.2-clutter-1.0

  1. Ubuntu Software

search for : system moniter extension

  1. install and configure performance

hostname

hostnamectl hostnamectl set-hostname cat /etc/hostname cat /etc/hosts

chinese config

emacs chinese input

sudo apt install fcitx download sougou for linux sudo dpkg -i sougou...... fcitx set global restart configuration to add sougou chinese

$ local -a |grep zh sudo apt-get -y install language-pack-zh-hans $ local -a |grep zh to see zh is installed

export LC~CTYPE~=zh~CN~.UTF-8 to language configuration and auto install drivers to zh~CN~.UTF-8 so in emacs can input sougou, here we go

chinese output pdf

for a orgmode file with 汉字 pandoc xxxx.org -o xxxx.pdf pandoc xxxx.org -o xxxx.pdf --pdf-engine=xelatex 如果没有汉字支持

fc-list -f "%{family}\n"  :lang=zh
pandoc test.org -o test.pdf --pdf-engine=xelatex -V mainfont="AR PL KaitiM GB"

找到支持的格式,再指明

sed


a add new line(s) after match with context behind a c replace the current line in match with context behind c i add context behind i before match s repace d delete


sed -rn '/2\/1/s/00/**/pg' test2.csv

  • sed:
  • -rn : no default output and allow \
  • ' ' : aufrufen
  • /2\/1: reg pattern
  • s: search
  • 00: all 00

-**: will be replaced by**

  • p: print
  • g: global replace
  • test2.csv: input file

sed 's/ //pg' test2.csv

Makefile

gcc 调用 make 来构造

格式

目标 : 依赖 Tab 命令

1example

实列文件:add.c head.h main.c maul.c sub.c 直接在terminal 用gcc :$ gcc add.c main.c sub.c -o app

Makefile : $ touch Makefile

app: main.c add.c sub.c mul.c
    gcc main.c add.c sub.c mul.c 

$ make

2修改后只编译改动后的文件

Makefile : $ touch Makefile

app: main.o add.o sub.o mul.o
    gcc main.o add.o sub.o mul.o -o app

main.o: main.c
    gcc -c main.c -o main.o

add.o: add.c
    gcc -c add.c -o add.o

sub.o: sub.c
    gcc -c sub.c -o sub.o

mul.o: mul.c
    gcc -c mul.c -o mul.o

$ make 所有源文件的修改过,即时间戳晚于生成的目标文件,则重新编译

3使用自动变量

$@ :目标 $< :第一个依赖 $^ :所有依赖 Makefile : $ touch Makefile

obj =   main.o add.o sub.o mul.o
target = app

$(target):$(obj)
    gcc $(obj) -o $(target)  // gcc $^ -o $@

%.o:%.c
    gcc -c $< -o $@

$ make

4增加可移植性

wildcard :查找指定目录下的指定类型文件 src = $(wildcard ./*.c) 将当前目录下所有的.c 找到,并赋给src

patsubst :匹配替换 obj = $(patsubst %.c, %.o, $(src)) 将src中的所有.c替换为.o

Makefile : $ touch Makefile

src = $(wildcard ./*.c)
obj = $(patsubst %.c, %.o $(src))
target = app

$(target):$(obj)
    gcc $^ -o $@

%.o:%.c
    gcc -c $< -o $@

$ make 此文件在别的目录下也能使用

5清洁中间的生成的不必要保存文件

make 一般直接执行终结目标,但是可以直接指定make的函数 clean : 删除不必要的文件,-f : 强制删除,不管有没有该文件,- : 前置-后,遇到错误执行,直接跳过

src = $(wildcard ./*.c)
obj = $(patsubst %.c, %.o $(src))
target = app

$(target):$(obj)
    gcc $^ -o $@

%.o:%.c
    gcc -c $< -o $@

clean:
    rm $(obj) $(target)
    rm $(obj) $(target) -f
    -rm $(obj) $(target) -f

$ make $ make clean

BetreibenSystem

Program execution level

Multi Process : Parallel single Process has more thread : Concurrency single thread can work in Synchronous or Asynchronous

Multi Process

queue communication

  1. one way communication server to client

    Server.c

    #include <stdio.h>
    #include "unistd.h"
    #include "sys/types.h"
    #include "stdlib.h"
    #include "signal.h"
    #include "sys/msg.h"
    #include "string.h"
    
    #define messagelen 124
    
    
    struct messqueue
    {
      long type;
      char message[messagelen];
      char ID[4];
    };
    
    
    int main(int argc, char *argv[])
    {
      int msgid;
      int key;
      int receivelen;
      int conut = 0;
      struct messqueue sendbuffer;
      sendbuffer.type = 100;
    
      key = ftok("./a.c", 'a');
      if (key < 0) {
        printf("create key for server failed \n");
        return -1;
      }
    
      //create the massage queue
      msgid= msgget(key, IPC_CREAT | 0777);
      if (msgid < 0) {
        printf("creat massage queue failed .\n");
        return -1;
      }
      printf("create massage queue success  with msgid %d.\n",  msgid);
    
    
      do {
        memset(sendbuffer.message, 0, messagelen);
        //input your massage
        printf("please input your massage you want to send to massage queue \n");
        scanf("%s", sendbuffer.message);
    
        //wirte the massage(which is now in your struct messqueue) into massage queue msgid
        msgsnd(msgid, (void *)&sendbuffer, strlen(sendbuffer.message), 0);
        conut++;
      }while (conut < 3);
    
      msgctl(msgid, IPC_RMID, NULL);
    
      system("ipcs -q");
      return 0;
    }
    
    

    Client.C

    #include <stdio.h>
    #include "unistd.h"
    #include "sys/types.h"
    #include "stdlib.h"
    #include "signal.h"
    #include "sys/msg.h"
    #include "string.h"
    
    #define messagelen 124
    
    
    struct messqueue
    {
      long type;
      char message[messagelen];
      char ID[4];
    };
    
    
    int main(int argc, char *argv[])
    {
      int msgid;
      int key;
      int receivelen;
      int conut = 0;
      struct messqueue sendbuffer;
      sendbuffer.type = 100;
    
      key = ftok("./a.c", 'a');
      if (key < 0) {
        printf("create key for server failed \n");
        return -1;
      }
    
      //create the massage queue
      msgid= msgget(key, IPC_CREAT | 0777);
      if (msgid < 0) {
        printf("creat massage queue failed .\n");
        return -1;
      }
      printf("create massage queue success  with msgid %d.\n",  msgid);
    
    
      do {
        memset(sendbuffer.message, 0, messagelen);
        //input your massage
        printf("please input your massage you want to send to massage queue \n");
        scanf("%s", sendbuffer.message);
    
        //wirte the massage(which is now in your struct messqueue) into massage queue msgid
        msgsnd(msgid, (void *)&sendbuffer, strlen(sendbuffer.message), 0);
        conut++;
      }while (conut < 3);
    
      msgctl(msgid, IPC_RMID, NULL);
    
      system("ipcs -q");
      return 0;
    }
    
    
  2. two ways communication server vs client

    Server.c

    #include <stdio.h>
    #include "unistd.h"
    #include "sys/types.h"
    #include "stdlib.h"
    #include "signal.h"
    #include "sys/msg.h"
    #include "string.h"
    
    #define messagelen 124
    
    
    struct messqueue
    {
      long type;
      char message[messagelen];
      char ID[4];
    };
    
    
    int main(int argc, char *argv[])
    {
      int msgid;
      int key;
      int receivelen;
      int conut = 0;
      pid_t pid;
      struct messqueue sendbuffer, receiverbuffer;
    
    
      key = ftok("./b.c", 'a');
      if (key < 0) {
        printf("create key for server failed \n");
        return -1;
      }
    
      //create the massage queue
      msgid= msgget(key, IPC_CREAT | 0777);
      if (msgid < 0) {
        printf("creat massage queue failed .\n");
        return -1;
      }
      printf("create massage queue success  with msgid %d.\n",  msgid);
    
      pid = fork();
    
      if (pid > 0) {   //server father process write tpye 100
        sendbuffer.type = 100;
    
        while(1) {
          memset(sendbuffer.message, 0, messagelen);
          //input your massage
          printf("please input your massage you want to send to massage queue \n");
          scanf("%s", sendbuffer.message);
    
          //wirte the massage(which is now in your struct messqueue) into massage queue msgid
          msgsnd(msgid, (void *)&sendbuffer, strlen(sendbuffer.message), 0);
          conut++;
        }
      }
    
      if (pid == 0) {    //server child process read tpye 200
        while (1) {
          memset(receiverbuffer.message, 0, messagelen);
          msgrcv(msgid, (void *)&receiverbuffer, messagelen, 200, 0);
          printf("the receive massage of massage queue in server is %s \n", receiverbuffer.message);
        }
    
      }
    
      msgctl(msgid, IPC_RMID, NULL);
    
      system("ipcs -q");
      return 0;
    }
    
    

    Client.c

    #include <stdio.h>
    #include "unistd.h"
    #include "sys/types.h"
    #include "stdlib.h"
    #include "signal.h"
    #include "sys/msg.h"
    #include "string.h"
    
    #define messagelen 124
    
    
    struct messqueue
    {
      long type;
      char message[messagelen];
      char ID[4];
    };
    
    
    int main(int argc, char *argv[])
    {
      int msgid;
      int key;
      int receivelen;
      int conut = 0;
      pid_t pid;
      struct messqueue sendbuffer, receiverbuffer;
    
    
      key = ftok("./b.c", 'a');
      if (key < 0) {
        printf("create key for server failed \n");
        return -1;
      }
    
      //create the massage queue
      msgid= msgget(key, IPC_CREAT | 0777);
      if (msgid < 0) {
        printf("creat massage queue failed .\n");
        return -1;
      }
      printf("create massage queue success  with msgid %d.\n",  msgid);
    
      pid = fork();
    
      if (pid == 0) { // client child process for write tpye 200
        sendbuffer.type = 200;
    
        while(1) {
          memset(sendbuffer.message, 0, messagelen);
          //input your massage
          printf("please input your massage you want to send to massage queue \n");
          scanf("%s", sendbuffer.message);
    
          //wirte the massage(which is now in your struct messqueue) into massage queue msgid
          msgsnd(msgid, (void *)&sendbuffer, strlen(sendbuffer.message), 0);
          conut++;
        }
      }
    
      if (pid > 0) {  // client child process read type 100
        while(1){
          memset(receiverbuffer.message, 0, messagelen);
          msgrcv(msgid, (void *)&receiverbuffer, messagelen, 100, 0);
          printf("the receive massage of massage queue in server is %s \n", receiverbuffer.message);
        }
      }
    
      msgctl(msgid, IPC_RMID, NULL);
    
      system("ipcs -q");
      return 0;
    }
    
    
    

pipe communication

  1. named

    1. In current directory: mkfifo("./myfifo", 0777);

    with mkfifo creat a file, so that other unrelated process can commu

    1. In one process : fd = open("./myfifo", O~WRONGLY~);

    open the file, and : write(fd, &process~inter~,1); change the pipe variable.

    1. In other process : fd = open("./myfifo",O~RDONLY~);

    open the file, and : while(process~inter~ == 0); can be controled by pipe variable

  2. unnamed

    1. In one process diff threads creat place for pipe : int fd[2]; one for main thread, one for new thread creat pipe : int ret = pipe(fd);

      in new thread : read(fd[0], &process~inter~ 1); if nothing to read, sleep in main thread do its stuff, after finish : write(fd[1], &process~inter~, 1); let new pthread run

      remeber: wirte at frist in fd[1], and then read at fd[0]

signal communication

  1. alarm

    alarm(10); wait for 10 seconds and kill itself send signal as 14 to itself

  2. kill

    kill(pid, 9); send signal 9 to pid process

  3. raise

    raise(9); == kill(getpid(), 9);

  4. pause

    pause(); stoped for ever

  5. signal

    signal(signal~ID~, self~function~); self function or SIG~ING~ or SIG~DFL~

  6. exit

    exit(0) will also send signal 17 (SIGCHID) to its father thread;

semaphore communication

  1. key

    key can be 2 differ

    1. For father and son process : IPC~PRIVATE~ :
    2. For unrelated process : self~def~ key
    
    int key;
    key = ftok("./a.c", 'a');
    if (key < 0) {
      printf("create key for server failed \n");
      return -1;
    }
    printf("create key for server success \n");
    
  2. memcpy

    memcpy(p, "niao",4);

  3. shmget

    shmid = shmget(IPC~PRIVATE~, 128, 0777); shmid = shmget(key, 128, IPC~CREAT~ | 0777);

  4. shmat

    char *p = (char *) shmat(shmid, NULL, 0); after mapping to p : can be manipulated scanf("%s", p); printf("%s", p);

  5. shmdt

    delete the mapping of p to shared memory shmdt(p); after that, the manipulation of p is not allowed, and well be segmention fault

  6. shmctl

    delete the created shared memory shmctl(shmid, IPC~RMID~, NULL); == iprcm -m shmid

  7. IPC manipulation

    show : ipcs -m(shared memory) -q(message queue) -s(semaphores) delete : ipcrm -m shmid /-q msgid /-s semid

  8. msgget

    msgid= msgget(IPC~PRIVATE~, 0777);

    #include <stdio.h>
    #include "unistd.h"
    #include "sys/types.h"
    #include "stdlib.h"
    #include "signal.h"
    #include "sys/msg.h"
    
    int main(int argc, char *argv[])
    {
      int msgid;
    
      msgid= msgget(IPC_PRIVATE, 0777);
      if (msgid < 0) {
        printf("creat massage queue failed .\n");
        return -1;
      }
    
      printf("create massage queue success  with msgid %d.\n",  msgid);
    
      system("ipcs -q");
      return 0;
    }
    
    
    
    ------ Nachrichtenwarteschlangen --------
    Schlüssel msqid      Besitzer   Rechte     Benutzt-Bytes Nachrichten 
    0x61091797 2          silin      777        0            0           
    0x00000000 4          silin      777        0            0           
    0x00000000 5          silin      777        0            0           
    0x00000000 6          silin      777        0            0           
    0x00000000 7          silin      777        0            0           
    0x00000000 8          silin      777        0            0           
    0x00000000 9          silin      777        0            0           
    0x00000000 10         silin      777        0            0           
    0x00000000 11         silin      777        0            0           
    0x00000000 12         silin      777        0            0           
    
    create massage queue success  with msgid 12.
    
  9. msgctl

    msgctl(msgid, IPC~RMID~, NULL); == ipcrm -q msgid

    #include <stdio.h>
    #include "unistd.h"
    #include "sys/types.h"
    #include "stdlib.h"
    #include "signal.h"
    #include "sys/msg.h"
    
    int main(int argc, char *argv[])
    {
      int msgid;
    
      msgid= msgget(IPC_PRIVATE, 0777);
      if (msgid < 0) {
        printf("creat massage queue failed .\n");
        return -1;
      }
    
      printf("create massage queue success  with msgid %d.\n",  msgid);
    
      system("ipcs -q");
      return 0;
    }
    
    
  10. msgsnd & msgrcv

    msgsnd(msgid, (void *)&sendbuffer, strlen(sendbuffer.message), 0);

    receivelen = msgrcv(msgid, (void *)&receiverbuffer, messagelen, 100, 0);

    #include <stdio.h>
    #include "unistd.h"
    #include "sys/types.h"
    #include "stdlib.h"
    #include "signal.h"
    #include "sys/msg.h"
    #include "string.h"
    
    #define messagelen 124
    
    
    struct messqueue
    {
      long type;
      char message[messagelen];
      char ID[4];
    };
    
    
    int main(int argc, char *argv[])
    {
      int msgid;
      int receivelen;
      struct messqueue sendbuffer, receiverbuffer;
      sendbuffer.type = 100;
      receiverbuffer.type = 100;
    
      //create the massage queue
      msgid= msgget(IPC_PRIVATE, 0777);
      if (msgid < 0) {
        printf("creat massage queue failed .\n");
        return -1;
      }
      printf("create massage queue success  with msgid %d.\n",  msgid);
    
      //input your massage
      printf("please input your massage you want to send to massage queue \n");
      scanf("%s", sendbuffer.message);
    
      //wirte the massage(which is now in your struct messqueue) into massage queue msgid
      msgsnd(msgid, (void *)&sendbuffer, strlen(sendbuffer.message), 0);
    
      //clear receiverbuffer.massage
      memset(receiverbuffer.message, 0, messagelen);
      //read massage to receiverbuffer from massage queue msgid
      receivelen = msgrcv(msgid, (void *)&receiverbuffer, messagelen, 100, 0);
    
      printf("the receiverbuffer massage have %s .\n", receiverbuffer.message);
      printf("the long is %d .\n", receivelen);
    
    
      msgctl(msgid, IPC_RMID, NULL);
    
      system("ipcs -q");
      return 0;
    }
    
    
    
    ------ Nachrichtenwarteschlangen --------
    Schlüssel msqid      Besitzer   Rechte     Benutzt-Bytes Nachrichten 
    0x61091797 2          silin      777        0            0           
    0x00000000 4          silin      777        0            0           
    0x00000000 5          silin      777        0            0           
    0x00000000 6          silin      777        0            0           
    0x00000000 7          silin      777        0            0           
    0x00000000 8          silin      777        0            0           
    0x00000000 9          silin      777        0            0           
    0x00000000 10         silin      777        0            0           
    0x00000000 11         silin      777        0            0           
    0x00000000 12         silin      777        0            0           
    
    create massage queue success  with msgid 14.
    please input your massage you want to send to massage queue 
    the receiverbuffer massage have
    the long is 6 .
    
  11. semget

    semid = semget(IPC~PRIVATE~,3 , 0777);

  12. semctl

    semctl(semid, 0, IPC~RMID~, NULL);

Multi Thread

1 pthread~create~.c

using pthread~create~ create new thread(thread~fun~) with arguements("new thread"). In new thread call function print~id~ with giving arguements.

This programm can't compiled in Babel, please save this as a .c file, and compile with -pthread

#include "apue.h"

void print_id(char *s)
{
  pid_t pid;
  pthread_t tid;

  pid = getpid();
  tid = pthread_self();

  printf("%s pid is %u, and tid is 0x%x\n", s, pid, (int) tid);
}

void *thread_fun(void *arg)
{
  printf("In son thread, can't get the father tid \n");

  print_id(arg);
  return (void *)0;
}

int main( )
{
  pthread_t ntid;
  int err;
  err = pthread_create(&ntid, NULL, thread_fun, "new thread");

  if (err != 0) {
    printf("create new thread is failed\n");
    return 0;
  }
  printf("In father thread, the new THREAS is 0x%x \n", (int)ntid );

  print_id("main thread");
  sleep(2);

  return 0;
}


2 pthread~id~.c

using pid = getpid() to get pid of current pthread

#include <stdio.h>
#include "unistd.h"
#include "sys/types.h"
#include "stdlib.h"
#include "signal.h"
#include "sys/msg.h"
#include "string.h"

int main( )
{
  pid_t pid;
  pthread_t tid;

  pid = getpid();
  tid = pthread_self();

  printf("pid is %d , and tid is %x\n", pid, (int)tid );
  return 0;
}


pid is 3406 , and tid is 960c4c0

3 pthread~jion~.c

pthread~jion~(tid, &reval) 可以回收主线程发起的副线程tid,并由 副线程指定返回值给reval.但是副线程如自己调用了 pthread~detach~(pthread-self()) 可以阻止主线程的jion

#include "apue.h"

void *thread_fun1(void *arg){
  printf("New thread out with return\n");
  return (void *)1;
}

void *thread_fun2(void *arg){
  printf("New thread out with pthread_exit\n");
  pthread_detach(pthread_self()); // detach it self
  pthread_exit((void *)2);
}


int main( )
{
  pthread_t tid1, tid2;
  int err1, err2;
  void  *reval1, *reval2;

  err1 = pthread_create(&tid1, NULL, thread_fun1, NULL); 
  err2 = pthread_create(&tid2, NULL, thread_fun2, NULL); 

  if (err1 || err2) {
    printf("The create of new thread is failed\n");
  }

  printf("the thread 1 has return as %d\n", pthread_join(tid1, &reval1) );
  printf("the thread 2 has return as %d\n", pthread_join(tid2, &reval2) );

  printf("the thread 1 has return code %d\n",(int*)reval1 );
  printf("the thread 2 has return code %d\n",(int*)reval2 );

  return 0;
}



4 pthread~cancel~.c

从主线程来的pthread~cancel~(tid)作用到tid的副线程时, 如果副线程设置为pthread~setcancelstate~(PTHREAD~CANCELDISABLE~, NULL) 则取消请求被忽视

如果副线程设置为pthread~setcancelstate~(PTHREAD~CANCELENABLE~, NULL); 则取消请求在下一个取消点被执行

如果副线程设置为pthread~setcanceltype~(PTHREAD~CANCELASYNCHRONOUS~, NULL); 则取消请求被立即执行

#include "apue.h"

void *thread_fun(void * arg){
  int stateval;
  int typeval;

  //  set cancel to be disable
  stateval = pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
  if (stateval != 0) {
    printf("set cancel state to disable is failed\n");
  }
  printf("I'm New thread here !\n");
  sleep(4);


  //set cancel to be enable, will be canceled at the first cancel point
  stateval = pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
  if (stateval != 0)
    printf("set cancel state to enable is failed\n");
  else
    printf("about to set cancel enable\n");   // print is a cancel point

  //set cancel to be enable and immediately
  typeval = pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  if (typeval != 0) {
    printf("set cancel state to immediately failed\n");
  }

  //cancel points
  printf("first place to cancel:\n");
  printf("second place to cancel:\n");
  return (void *)20;
}



int main( )
{
  pthread_t tid;
  int err, cval, jval;
  void * rval;

  err = pthread_create(&tid, NULL, thread_fun, NULL);
  if (err != 0) {
    printf("creat new thread is failed\n");
    return 0;
  }
  sleep(2);

  cval = pthread_cancel(tid);
  if (cval != 0) {
    printf("cancel the new thread is failed\n");
    return 0;
  }

  jval = pthread_join(tid, &rval);
  if (jval != 0) {
    printf("join thread  is failed\n");
    return 0;
  }
  printf("new thread has return code of %d\n", (int) rval );

  return 0;
}

5 pthread~rwlock~.c

pthread~rwlockt~ rwlock; 声明 pthread~rwlockinit~(&rwlock); 初始化 pthread~rwlockwrlock~(&rwlock); 写锁 pthread~rwlockrdlock~(&rwlock); 读锁 pthread~rwlockunlock~(&rwlock); 解锁 pthread~rwlockdestroy~(&rwlock); 销锁

#include "apue.h"
int num;
pthread_rwlock_t rwlock;

void * thread_fun1(void *arg){
  int err;
  sleep(1);
  pthread_rwlock_wrlock(&rwlock);  // write mode lock
  // pthread_rwlock_rdlock(&rwlock);   // read mode lock

  printf("thread 1 print num as %d\n",num );
  sleep(5);
  printf("thread 1 is over \n");

  pthread_rwlock_unlock(&rwlock);
  return (void *)0;
}

void * thread_fun2(void *arg){
  int err;
  pthread_rwlock_wrlock(&rwlock);
  //  pthread_rwlock_rdlock(&rwlock);

  printf("thread 2 print num as %d\n",num );
  sleep(5);
  printf("thread 2 is over \n");

  pthread_rwlock_unlock(&rwlock);
  return (void *)0;
}

int main( )
{
  pthread_t tid1, tid2;
  int err;

  err = pthread_rwlock_init(&rwlock, NULL);
  if (err) {
    printf("init failed\n");
    return 0;
  }

  err = pthread_create(&tid1, NULL ,thread_fun1, NULL);
  if (err) {
    printf("create of the first thread fail\n");
    return 0;
  }

  err = pthread_create(&tid2, NULL ,thread_fun2, NULL);
  if (err) {
    printf("create of the second thread failed\n");
    return 0;
  }

  pthread_join(tid1, NULL);
  pthread_join(tid2, NULL);

  pthread_rwlock_destroy(&rwlock);

  return 0;
}




6 pthread~attr~.c

seeing pthread~attr~.c pthread~attrinit~(&attr) using : pthread~attrsetdetachstate~(&attr, PTHREAD~CREATEDETACHED~); OR: pthread~attrsetdetachstate~(&attr, PTHREAD~CREATEJOINABLE~); 决定该线程是否可以被jion.

#include "apue.h"

void *thread_fun1(void *arg)
{
  printf("I am new thread  1\n");
  return (void *)1;
}


void *thread_fun2(void *arg)
{
  printf("I am new thread  2 \n");
  return (void *)2;
}

int main(int argc, char *argv[])
{
  pthread_t tid1, tid2;
  int err;

  //def attr and init and set to be spreate
  pthread_attr_t attr;
  pthread_attr_init(&attr);
  //  pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);  

  err = pthread_create(&tid1, &attr, thread_fun1, NULL);
  if (err) {
    printf("create new thread 1 failed \n");
    return 0;
  }

  err = pthread_create(&tid2, NULL, thread_fun2, NULL);
  if (err) {
    printf("create new thread 2 failed \n");
    return 0;
  }

  err = pthread_join(tid1, NULL);
  if (!err) 
    printf("join thread 1 success \n");
  else 
    printf("jion thread 1 failed \n");


  err = pthread_join(tid2, NULL);
  if (!err) 
    printf("join thread 2 success \n");
  else 
    printf("jion thread 2 failed \n");

  pthread_attr_destroy(&attr);

  return 0;
}



7 pthread~mutex~.c

pthread~mutexlock~(&mutex) 和 pthread~mutexunlock~(&mutex) 可以锁住之间的的任何变量, 所以不同线程之间的访问和赋值只能错开时间, 这样就不会造成线程之间变量值不受控制的错误

#include "apue.h"

struct student{
  int age;
  int size;
} stu;

int i;
pthread_mutex_t mutex;

void *thread_fun1(void *arg){
  while(1){
    //    pthread_mutex_lock(&mutex);
    stu.age = i;
    stu.size = i;
    i++;
    if (stu.age != stu.size) {
      printf("thread 1 %d, %d,\n", stu.age, stu.size);
      break;
    }
    //    pthread_mutex_unlock(&mutex);
  }
  return (void *)0;
}


void *thread_fun2(void *arg){
  while (1) {
    //    pthread_mutex_lock(&mutex);
    stu.age = i;
    stu.size = i;
    i++;
    if (stu.age != stu.size) {
      printf("thread 2 %d, %d,\n", stu.age, stu.size);
    }
    //    pthread_mutex_unlock(&mutex);
  }
  return(void *)0;
}

int main( )
{
  pthread_t tid1, tid2;
  int err1, err2;

  err1 = pthread_create(&tid1, NULL, thread_fun1, NULL);
  err2 = pthread_create(&tid2, NULL, thread_fun2, NULL);  
  if (err1 || err2) {
    printf("the create o pthread 1 and pthread 2 failed\n");
  }

  pthread_join(tid1, NULL);
  pthread_join(tid2, NULL);

  return 0;
}


8 pthread~interpetercontroll~.c

用主线程给一个可交换变量赋值,来控制副进程的执行, only if in main thread, parameter interpeter be assigned to 1, in side thread can start to run.

#include <stdio.h>
#include "stdlib.h"
#include <unistd.h>
#include "pthread.h"

int interpeter = 0;

void *mythread(void *num){
  while(interpeter == 0);
  int i = 0;
  for (i = 0; i < 10; ++i) {
    printf("In my thread there is %d\n", i);
    usleep(100);
  }
  return (void *)0;
}

int main(int argc, char *argv[])
{
  pthread_t tid;
  int err;
  err = pthread_create(&tid, NULL, mythread, NULL);
  if (err < 0) {
    printf("create my thread failed\n");
    return -1;
  }
  int i = 0;
  for (i = 0; i < 10; ++i) {
    printf("In main thread there is %d\n", i);
    usleep(100);
  }
  interpeter = 1;
  sleep(10);
  return 0;
}



9 pthread~passstruct~.c

将一个结构体通过pthread~create~()的参数传给副进程,注意在副进程中的 结构体转化

#include "apue.h"

struct student {
  int age;
  char name[10];
  char subject[10];
};

void *thread_fun(void *stu)
{
  printf("In the constuction we have age : %d, name : %s, and subject %s.\n", ((struct  student *)stu)->age,((struct student *)stu)->name, ((struct student *)stu)->subject);
  return (void *)0;
}

int main( )
{
  pthread_t tid;
  int err;
  void * val;

  struct student stu;
  stu.age = 20;
  memcpy(stu.name, "xiang", 10);
  memcpy(stu.subject, "phyics", 10);

  err = pthread_create(&tid, NULL, thread_fun, (void *)&stu);
  if (err != 0) {
    printf("the new thread is failed to create\n");
    return  0;
  }
  pthread_exit(val);
  return 0;
}





10 pthread~stackattr~.c

在系统支持的条件下,获取栈的大小,并作出调整

#include "apue.h"

pthread_attr_t attr;

void *thread_fun(void *arg){

  size_t stacksize;

#ifdef _POSIX_THREAD_ATTR_STACKSIZE
  pthread_attr_getstacksize(&attr, &stacksize);
  printf("new thread stack size is %d \n", (int)stacksize );  //获取默认栈大小
  //更改 has to be greater than 16384, otherwise will be default
  pthread_attr_setstacksize(&attr, 100000);
  pthread_attr_getstacksize(&attr, &stacksize);
  printf("new thread stack size is %d \n", (int)stacksize );  //获取设置栈大小
#endif // _POSIX_THREAD_ATTR_STACKSIZE


  return (void *)1;
}


int main(int argc, char *argv[])
{
  pthread_t tid;
  int err;

  pthread_attr_init(&attr);

  //设置为可连接的分离属性
  pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);

  //check if system support this
#ifdef _POSIX_THREAD_ATTR_STACKSIZE
  pthread_attr_setstacksize(&attr, PTHREAD_STACK_MIN);
#endif // _POSIX_THREAD_ATTR_STACKSIZE

  err = pthread_create(&tid, &attr, thread_fun, NULL);
  if (err) {
    printf("create new thread failed \n");
    return 0;
  }
  pthread_join(tid ,NULL);
  return 0;
}


Stoket

Git

tips

Raw 文件
git rm --cached file, will only delete it in git, but still in my local directory

Git installation in Linux

  1. sudo apt install git

  2. local configuration

git  config --global user.name "username1"
git  config --global user.email "email1"

git config --list

  1. in local terminal
ssh-keygen -t rsa -C "email2"

and then just all enter as default warming: email1 == email2

Webconfig

1. go to Fold Docu1, and in terminal git init to create local  repository
2. apply github count with:
   Email: email3
   Username: username3
   Password:xxxx
3. in setting add ssh key from local document: ./ssh/id_rsa.pub
4. create web repository with name Docu2
   Warming: Docu1 == Docu2

Connection

1. in local computer Docu1, create our files and prepare to push to
   Github
2. git add && git commit -m ""
3. git remote add origin HTTPS/SSH(of the created web repository)
   warming: with  HTTPS will be ask the Username:username3 and
   password:xxxx every time for the push, but SSH note
4. git push -u origin master
5. username3 and xxxx if necessary
6. later push it only use git push origin master

Magit

C-x g  : open the git buffer
S or s : to stage
C      : to commit 
C-c C-c : to finish commit
P and p to push

Git branch

git branch 创建development分支

branch 创建 新分支
创建新的分支: git branch development
带着全部家当去新的分支: git checkout development
git add -A 
git commit -m "development"
git push -u origin development

git merge 可以 merge mybranch分支到master分支

merge 融合分支
如果此时只有development分支改变,可以直接回到master, 把development分支
merge 过来   git merge development

git checkout master
git pull origin master
git branch --merged
git merge development
git push origin master

删除mybranch分支

git branch --merged
git branch -d mybrauch
git branch -a 
git push origin --delete mybrauch

git rm

  1. git rm --cached file

    编辑当前文件后,已提交(已 add),想撤出索引 :    git rm --cached  file
    after that, I can check the delete file with git status or git diff --cached.
    
  2. recover after git rm

    if I want , I can git add * to call all back again, but nothing to commit
    
  3. confirm to delete file in local directory

    if I ready want to delete this,
    using rm file  delete the file in local directory, 
    but git status and diff --cached remands this still, 
    only after commit, there's no signal for the deleted file anymore.
    
  4. recover after delete in local directory

    git reflog
    git reset --hard ID
    

git multi commit

commit 添加提交 和上次commit提交融合,不产生新的提交记录: git commit --amend

remote branch

git checkout -t origin/ui-mockup

commands to recover

after only save


git diff can see the different comparing to last time commit git checkout -- file git diff: NULL, file has been recovered


after git add file


git diff dit diff :NULL git diff --cached can see the different comparing to the last time commit git reset HEAD file git diff -- cached : NULL git checkout -- file file has been recovered


after git commit file

编辑后,强制回到最近一次添加索引的版本:        git reset --hard HEAD
编辑后,强制回到最近倒数第二次添加索引的版本:   git reset --hard HEAD~
编辑后,强制回到最近倒数第n次添加索引的版本:    git reset --hard HEAD~n

如果将HEAD换成对应的ID, 也可以回到之前相应的版本。 但是如果想再回去,
又没有记住之前的ID, 可以用,       git reflog 查询.

GWDG

  1. as student of Göttingen send email to support@gwdg.de with uni email, asking for freischaltung of cloud server
  2. got https://gwdg.de Dienst-> GWDG cloud server -> self service create Instance if with my ssh, the connect can be without password, but still need to aktiv
  3. where the instance is created, use the VNS to aktiv the konto, remember to save the password ssh cloud@ip

Google cloud

Certificate

  • First generate the self-singed certificate: Set CN to localhost,

    openssl req -new -x509 -nodes -keyout key.pem -sha256 -days 365 -out cert.pem
    sudo cp cert.pem /etc/pki/ca-trust/source/anchors/
    sudo update-ca-trust
    
  • First generate a new key, and Then create a CSR from it:

    openssl genrsa -out test.key 2048
    openssl req -new -key test.key -out test.csr
    
  • creat extenation file test.ext, for domain name or DNS

    1 authorityKeyIdentifier=keyid,issuer
    2 basicConstraints=CA:FALSE
    3 keyUsage =digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
    4 subjectAltName = @alt_names
    5
    6 [alt_names]
    7 DNS.1 = localhost
    8 DNS.2 = test.dev
    
  • Create a new signed certificate for extended information

    openssl x509 -req -in test.csr -CA cert.pem -CAkey key.pem -CAcreateserial \
    -out test.crt -days 365 -sha256 -extfile test.ext    
    
  • signed by Let's Encrypt

    sudo certbot certonly --standalone
    
  • DONe

Problem

System limit for number of file watchers reached

sudo sysctl -w fs.inotify.max~userwatches~=100000 reboot

ls

Docker

sudo docker rm $(sudo docker ps -aq)
sudo docker rmi $(sudo docker images -aq)

opencv

sudo cmake -DCMAKE~INSTALLPREFIX~:PATH=/home/si/Dokumente/opencv/libopencv .. make make install export LD~LIBRARYPATH~=$LD~LIBRARYPATH~:/home/si/Dokumente/opencv/libopencv/lib

Warp


Ctrl f move cousur to left, accept the auto complete Ctrl N next block Ctrl P provious block



title: Algorithm

#+STARTUP: overview

Bubble

Algorithm

each time compare itself with the next, if smaller, exchange them after each epoch, the biggest will be right localed. with the cursor moving, always with the so far biggest

A[a] for a -> 0, 1, 2, 3....l
FOR i -> 0, 1, 2...l-2:
    FOR j -> 0, 1, 2...l-2-i:
        IF A[j] > A[j+1]:
            exchange A[j]:A[j+1]

Python

A = [2,5,6,8,45,68,98,42,12,7,156,158,9]
lang = len(A)
for i in range(lang-2):
    for j in range(lang-i-1):
        if A[j] > A[j+1]:
            A[j], A[j+1] = A[j+1], A[j]
print(A)            
[2, 5, 6, 7, 8, 9, 12, 42, 45, 68, 98, 156, 158]

java

class BubbleSorting
{
    public static void main(String[] args)
    {
        int A[] = {2,5,6,8,45,68,98,42,12,7,156,158,9};
        int langdu = A.length;

        for (int i = 0; i <= langdu-2; i++) {
            for (int j = 0; j <= langdu-2-i; j++) {
                if (A[j] > A[j+1]) {
                    int tmp = A[j+1];
                    A[j+1] = A[j];
                    A[j] = tmp;
                }
            }
        }
        for (int a:A){
            System.out.printf("%d ", a);
        }
    }
}

2 5 6 7 8 9 12 42 45 68 98 156 158 

C/C++

int main(int argc, char *argv[])
{
  int list[] = {2,5,6,8,45,68,98,42,12,7,156,158,9};
  int langdu = sizeof(list) / sizeof(int);

  void swap(int *a, int *b){
    int tmp = *b;
    *b = *a;
    *a = tmp;
  }

  for (int i = 0; i <= langdu-2; ++i) {
    for ( int j=0; j <= langdu-2-i;++j) {
      if (list[j] > list[j+1]) {
        swap(&list[j], &list[j+1]);
      }
    }
  };

  for (int k = 0; k < langdu; ++k) {
    printf("%d  ",*(list+k));
  }
  return 0;
}

2  5  6  7  8  9  12  42  45  68  98  156  158

Select

Algorithm

find the sofar biggest or smallest one of each epoch at the front of list, after each epoch put it to the right place.

A[a] for a -> 0, 1, 2....l
FOR i -> 0, 1, 2...l-1:
    FOR j -> 0, 1, 2....l-1-i:
        IF A[j] > A[0]:
            exchange(A[j], A[0])
    exchange(A[0], A[l-1-i])

Python

A = [2,5,6,8,45,68,98,42,12,7,156,158,9]
lang = len(A)
for i in range(lang):
    for j in range(lang-i):
        if A[j] > A[0]:
            A[j], A[0] = A[0], A[j]
    A[0], A[lang-1-i] = A[lang-1-i], A[0]
print(A)

[2, 5, 6, 7, 8, 9, 12, 42, 45, 68, 98, 156, 158]

Java

class SelectSorting
{
    public static void main(String[] args)
    {
        int A[] = {2,5,6,8,45,68,98,42,12,7,156,158,9};
        int langdu = A.length;
        for (int i = 0; i <= langdu-1; i++) {
            for (int j = 0; j <= langdu-1-i; j++) {
                if (A[j] > A[0]) {
                    int tmp = A[j];
                    A[j] = A[0];
                    A[0] = tmp;
                }
            }
            int tmp = A[langdu-1-i];
            A[langdu-1-i] = A[0];
            A[0] = tmp;
        }
        for (int var : A) {
            System.out.printf("%d ", var);
        }
    }
}

2 5 6 7 8 9 12 42 45 68 98 156 158 

C/C++

int main(int argc, char *argv[])
{
  int list[] = {2,5,6,8,45,68,98,42,12,7,156,158,9};
  int langdu = sizeof(list) / sizeof(int);
  int i, j;
  void swap(int *a, int *b){
    int tmp = *b;
    *b = *a;
    *a = tmp;
  }
  for (i = 0; i <= langdu -1; ++i) {
    for (j = 0; j <= langdu-1-i; ++j) {
      if (list[j] > list[0]) {
        swap(&list[j], &list[0]);
      }
    }
    swap(&list[0], &list[langdu-1-i]);
  }
  for (int k = 0; k < langdu; ++k) {
    printf("%d ",*(list+k));
  }
  return 0;
}


2 5 6 7 8 9 12 42 45 68 98 156 158

Insert

Algorithm

A[a] for a -> 0, 1, 2....l-1
for i -> 1, 2...l-1:
    value <- A[i]
    index <- i
    while(A[index-1] > value && index > 0)
        A[index] = A[index-1]
        index--        
    A[index] <- value

Python

list1 = [2, 1, 3, 4, 5, 3, 6, 7, 8, 4, 9, 45, 9,34, 23,345, 546,20, 23465, 90, 19]
langdu = len(list1)
for i in range(1, langdu):
    value = list1[i]
    index = i
    while(index > 0 and list1[index-1] > value):
        list1[index] = list1[index-1]
        index -= 1
    list1[index] = value
print(list1)
[1, 2, 3, 3, 4, 4, 5, 6, 7, 8, 9, 9, 19, 20, 23, 34, 45, 90, 345, 546, 23465]

Java

class Inserting
{
    public static void main(String[] args)
    {
        int list1 [] = {2, 1, 3, 4, 5, 3, 6, 7, 8, 4, 9, 45, 9,34, 23,345, 546,20, 23465, 90, 19};
        int langdu = list1.length;
        for (int i = 1; i < langdu; i++) {
            int value = list1[i];
            int index = i;
            while(index > 0 && list1[index-1] > value) {
                list1[index] = list1[index-1];
                index--;
            }
            list1[index] = value;
        }
        for (int var :list1) {
            System.out.printf("%d ", var);        
        }
    }
}
1 2 3 3 4 4 5 6 7 8 9 9 19 20 23 34 45 90 345 546 23465 

C/C++

int main(int argc, char *argv[])
{
  int A[] = {2, 1, 3, 4, 5, 3, 6, 7, 8, 4, 9, 45, 9,34, 23,345, 546,20, 23465, 90, 19};
  int langdu = sizeof(A)/sizeof(int);
  for (int i = 1; i < langdu; ++i) {
    int value = A[i];
    int index = i;
    while (index > 0 && A[index-1] > value) {
      A[index] = A[index-1];
      index--;
    }
    A[index] = value;
  }
  for (int i = 0; i < langdu; ++i) {
    printf("%d ",A[i] );
  }
  return 0;
}

1 2 3 3 4 4 5 6 7 8 9 9 19 20 23 34 45 90 345 546 23465
int main(int argc, char *argv[])
{
  int A[] = {2, 1, 3, 4, 5, 3, 6, 7, 8, 4, 9, 45, 9,34, 23,345, 546,20, 23465, 90, 19};
  int langdu = sizeof(A)/sizeof(int);
  insert(A, langdu);
  for (int i = 0; i < langdu; ++i) {
    printf("%d ",A[i] );
  }
  return 0;
}
void insert(int A[], int langdu){
  for (int i = 1; i < langdu; ++i) {
    int value = A[i];
    int index = i;
    while (index > 0 && A[index-1] > value) {
      A[index] = A[index-1];
      index--;
    }
    A[index] = value;
  }
  return;

}

1 2 3 3 4 4 5 6 7 8 9 9 19 20 23 34 45 90 345 546 23465

merge

Algorithm

A[a] for a -> 0, 1, 2.....l-1
ll = 0
rr = l-1
mergersort(A, ll, rr)

mergersort(A, ll, rr)
  solang ll < rr
    dd = (ll+rr)/2
    A1[a] for a-> ll...dd
    A2[a] for a -> dd+1..rr
    mergersort(A1, ll, dd)
    mergersort(A2, dd+1, rr)
    merge(A1, ll, dd, A2, dd+1, rr)
  else return

merge(A1, A2)
  A1[i] for i -> 0...I
  A2[j] for j -> 0...J
  C[k]  for k -> 0....I+J
  if A1[i] > A2[j] && i < I && j < J
    C[k] <- A2[j]
    k++
    j++
  if i < I
  C[k...k+(I-i)] <- A1[i...I]
  if J < J
  C[k...k+(J-j)] <- A2[j...J]

A[a] for a -> 0, 1, 2....l-1
mergersort(A)

mergersort(A):
  if len(A) > 1:
    A1, A2 <- A
    A1 =  mergersort(A1)
    A2 =  mergersort(A2)
    return  merge(A1, A2)
  else return A
merge(A1, A2):
  A1[i] for i -> 0...I
  A2[j] for j -> 0...J
  C[k] for k -> 0...I+J
  while i < I and j < J:
    if A1[i] > A2[j]:
      C[k] <- A2[j]
      j++
    else C[k] <- A1[i]
      i++
    k++
  while i <= I
   C[k] <- A1[i]
  while j <= J
  C[k] <- A2[j]
 return C

Python

def mergesort(list1):
    if len(list1) <= 1:
        return list1
    mid = int(len(list1)/2)
    lista = list1[:mid]
    listb = list1[mid:]
    lista = mergesort(lista)
    listb = mergesort(listb)
    return merge(lista, listb)

def merge(lista, listb):
    result = []
    i = 0
    j = 0
    while(i < len(lista) and j < len(listb)):
        if lista[i] > listb[j]:
            result.append(listb[j])
            j += 1
        else:
            result.append(lista[i])
            i += 1
    result += lista[i:]
    result += listb[j:]
    return result
list1 = [2, 1, 3, 4, 5, 3, 6, 7, 8, 4, 9, 45, 9,34, 23,345, 546,20, 23465, 90, 19]
langdu = len(list1)
list1 = mergesort(list1)
print(list1)
[1, 2, 3, 3, 4, 4, 5, 6, 7, 8, 9, 9, 19, 20, 23, 34, 45, 90, 345, 546, 23465]

Java

mit index augenment

import java.util.*;
class Merging
{
    public static void main(String[] args)
    {
        int a [] = {2, 1, 3, 4, 5, 3, 6, 7, 8, 4, 9, 45, 9,34, 23,345, 546,20, 23465, 90, 19};
        int langdu = a.length-1;
        mergsort(a, 0, langdu );
        for(int var : a){
            System.out.printf("%d ", var);
        }
    }
    private static void mergsort(int [] a, int lo, int hi){
        if (lo >= hi) {
            return;
        }
        int mid = lo + (hi-lo)/2;
        mergsort(a, lo, mid);
        mergsort(a, mid+1, hi);
        merge(a, lo, mid, hi);
    }
    private static void merge(int [] a, int lo, int mid, int hi){
        int [] news = new int [hi-lo+1];
        int p = lo;
        int q = mid+1;
        int index = 0;
        while(p <= mid && q <= hi){
            if (a[p] > a[q]) {
                news[index++] = a[q++];
            }else{
                news[index++] = a[p++];
            }
        }
        while(p <= mid){
            news[index++] = a[p++];
        }

        while(q <= hi){
            news[index++] = a[q++];
        }
        System.arraycopy(news, 0, a, lo, hi-lo+1);
    }
}

1 2 3 3 4 4 5 6 7 8 9 9 19 20 23 34 45 90 345 546 23465 

without index augenment

import java.util.*;
class Merginge
{
    public static void main(String[] args)
    {
        int a [] = {2, 1, 3, 4, 5, 9, 7, 8, 6, 10, 2, 1, 3, 4, 5, 3, 6, 7, 8, 4, 9, 45, 9,34, 23,345, 546,20, 23465, 90, 19};
        int [] result = mergsort(a);
        for(int var : result){
            System.out.printf("%d ", var);
        }
    }
    private static int [] mergsort(int [] a){
        if (a.length <= 1) {
            return a;
        }
        int mid = a.length/2;
        int [] left = new int [mid];
        int [] right = new int [a.length - mid];
        for (int i = 0; i < mid; i++) {
            left[i] = a[i];
                }
        for (int i = mid; i < a.length; i++) {
            right[i-mid] = a[i];
                }
        left = mergsort(left);
        right = mergsort(right);
        return merge(left, right);
    }
    private static int[] merge(int [] left, int [] right){
        int lenleft = left.length-1;
        int leftindex = 0;
        int lenright = right.length-1;
        int rightindex = 0;
        int [] result = new int[lenleft+lenright+2];
        int index = 0;
        while(leftindex <= lenleft && rightindex <= lenright){
            if (left[leftindex] > right[rightindex]) {
                result[index++] = right[rightindex++];
            }else{
                result[index++] = left[leftindex++];
            }
        }
        while(leftindex <= lenleft){
            result[index++] = left[leftindex++];
        }
        while(rightindex <= lenright){
            result[index++] = right[rightindex++];
        }
        return result;
    }
}

1 1 2 2 3 3 3 4 4 4 5 5 6 6 7 7 8 8 9 9 9 10 19 20 23 34 45 90 345 546 23465 

C/C++

#include <stdio.h>
#include <stdlib.h>
#define N 7
void merge(int arr[], int low, int mid, int high){
    int i, k;
    int *tmp = (int *)malloc((high-low+1)*sizeof(int));
    int left_low = low;
    int left_high = mid;
    int right_low = mid + 1;
    int right_high = high;
    for(k=0; left_low<=left_high && right_low<=right_high; k++){
        if(arr[left_low]<=arr[right_low]){
            tmp[k] = arr[left_low++];
        }else{
            tmp[k] = arr[right_low++];
        }
    }
    if(left_low <= left_high){  
      for(i=left_low;i<=left_high;i++)
        tmp[k++] = arr[i];
    }
    if(right_low <= right_high){
      for(i=right_low; i<=right_high; i++)
        tmp[k++] = arr[i];
    }
    for(i=0; i<high-low+1; i++)
        arr[low+i] = tmp[i];
    free(tmp);
    return;
}
void merge_sort(int arr[], unsigned int first, unsigned int last){
    int mid = 0;
    if(first<last){
        mid = (first+last)/2; /* 注意防止溢出 */
        merge_sort(arr, first, mid);
        merge_sort(arr, mid+1,last);
        merge(arr,first,mid,last);
    }
    return;
}
int main(){
    int i;
    int a[N]={32,12,56,78,76,45,36};
    printf ("排序前 \n");
    for(i=0;i<N;i++)
        printf("%d\t",a[i]);
    merge_sort(a,0,N-1);  // 排序
    printf ("\n 排序后 \n");
    for(i=0;i<N;i++)
        printf("%d\t",a[i]); printf("\n");
    system("pause");
    return 0;
}

排序前 
32    12  56  78  76  45  36  
 排序后 
12    32  36  45  56  76  78

quick

Algorithm

A[a] for a -> 0, 1, 2...l-1:
quicksort(A, 0, l-1)

quicksort(A, start, end):
  if  start >= end:
    return;
  else:
    pivot = A[start]
    int i = start
    int j = end
    while(i != j):
      whil (j > i && A[j] > pivot):
          j--
      exchange(A[i], A[j])
      while(i < j && A[i] < pivot):
          i++
      exchange(A[i], A[j])

    quicksort(A, start, i+1)
    quicksort(A, i+1, end)

Python

def quicksort(A, start, end):
    if start >= end:
        return
    pivot = A[start]
    i = start
    j = end
    while i != j:
        while j > i and A[j] >= pivot:
            j -= 1
        A[i], A[j] = A[j], A[i]
        while i < j and A[i] <= pivot:
            i += 1
        A[i], A[j] = A[j], A[i]
    quicksort(A, start, j-1)
    quicksort(A, i+1, end)
    return



list1 = [2, 1, 3, 4, 5, 3, 5, 7, 8, 45,  9, 25,
         34, 23, 345, 546, 20, 23465, 90, 19]
langdu = len(list1)
quicksort(list1, 0, langdu-1)
print(list1)
[1, 2, 3, 3, 4, 5, 5, 7, 8, 9, 19, 20, 23, 25, 34, 45, 90, 345, 546, 23465]

Java

class Quicking
{
    public static void main(String[] args)
    {
        int a [] = {2, 1, 3, 4, 5,9087, 3, 6, 7, 8, 4, 9, 45, 9,34, 23,345, 546,20, 23465, 90, 19};
        int langdu = a.length-1;
        quicksort(a, 0, langdu);
        for (int var: a) {
            System.out.printf("%d ", var);
        }
    }
    private static void quicksort(int [] a, int start, int end ){
        if (start >= end) {
            return;
        }
        int pivot = a[start];
        int i = start;
        int j = end;
        while(i != j){
            while(j > i && a[j] >= pivot){
                j--;
            }
            int tmp = a[j];
            a[j] = a[i];
            a[i] = tmp;
            while(i < j && a[i] <= pivot){
                i++;
            }
            tmp = a[j];
            a[j] = a[i];
            a[i] = tmp;
        }
        quicksort(a, start, i-1);
        quicksort(a, i+1, end);
    }
}

1 2 3 3 4 4 5 6 7 8 9 9 19 20 23 34 45 90 345 546 9087 23465 

C/C++

  void swap(int *a, int *b){
    int tmp = *b;
    *b = *a;
    *a = tmp;
  }

  void quicksort(int a[], int start, int end){
    if (start >= end) {
      return;
    }
    int pivot = a[start];
    int i = start;
    int j = end;
    while (i != j) {
      while (j > i && a[j] > pivot) 
        j--;
      swap(&a[i], &a[j]);
      while (i < j && a[i] < pivot) 
        i++;
      swap(&a[i], &a[j]);
      quicksort(a, start, i-1);
      quicksort(a, i+1, end);
      return;
    }
  }

int main(int argc, char *argv[])
{
  int A[] = {2, 1, 3, 4, 5, 3, 6, 7, 8, 4, 9, 45, 9,34, 23,345, 546,20, 23465, 90, 190};
  int langdu = sizeof(A)/sizeof(int);
  quicksort(A, 0, langdu-1);
  for (int i = 0; i < langdu; ++i) {
    printf("%d ", A[i]);
  }
  return 0;
}
1 2 3 4 3 4 5 6 7 8 9 9 20 23 34 45 190 345 546 90 23465

heap

Algorithm


build~heap~() build all the data to heap heapify(list, n, i) from i on, can only grante that, the frist is the biggest


at frist build the heap, and then each time take the biggest one n:length, i the startup

heapify(list, n, i){  
  leftchild = 2i+1
  rightchild = 2i+2
  maxindex = i
  if leftchild < n && list[leftchild] > list[maxindex]:
    maxindex = leftchild
  if rightchild < n && list[rightchild] > list[maxindex]:
    maxindex = rightchild
  if maxindex != i:
    exchange(list[maxindex], list[i])
    heapify(list, n, maxindex)
  }
build_heap(list, n){
  last_parent = (n-1)/2
  for i -> last_parent....0:
    heapify(list, n, i) 
  }


build_heap(list, n)
for i -> n-1....0:
  swap(list, i, 0)
  heapify(list, i, 0)

python

def heapify(list1, n, i):
    leftchild = 2*i+1
    rightchild = 2*i +2
    maxindex = i
    if leftchild < n and list1[leftchild] > list1[maxindex]:
        maxindex = leftchild
    if rightchild < n and list1[rightchild] > list1[maxindex]:
        maxindex = rightchild
    if maxindex != i:
        list1[maxindex], list1[i] = list1[i], list1[maxindex]
        heapify(list1, n, maxindex)

def heap_build(list1, n):
    last_parent = (n-1)//2
    for i in range(last_parent+1):
        j = last_parent-i
        heapify(list1, n, j)


list1 = [2, 1, 3, 4, 5, 3, 5, 7, 8, 45,  9, 25, 34, 23, 345, 546, 20, 23465, 90, 19]
langdu = len(list1)
heap_build(list1, langdu)
print(list1)
for i in range(langdu):
    j = langdu-1-i
    list1[0], list1[j] = list1[j], list1[0]
    heapify(list1, j, 0)

print(list1)

[23465, 546, 345, 90, 45, 34, 23, 20, 8, 19, 9, 25, 3, 3, 5, 7, 1, 2, 4, 5]
[1, 2, 3, 3, 4, 5, 5, 7, 8, 9, 19, 20, 23, 25, 34, 45, 90, 345, 546, 23465]

Java

class HeapSorting
{
    public static void main(String[] args)
    {
        int a [] = {2, 1, 3, 4, 5,9087, 3, 6, 7, 8, 4, 9, 45, 9,34, 23,345, 546,20, 23465, 90, 190};
        int langdu = a.length;
        build_heap(a, langdu);
        for (int i = langdu-1; i >= 0; i--) {
            int tmp = a[0];
            a[0] = a[i];
            a[i] = tmp;
            heapify(a, i, 0);
        }
        for (int i = 0; i < langdu; i++) {
            System.out.printf("%d ", a[i]);
        }
    }
    private static void heapify(int a[], int n, int i){
        int leftchild = i*2+1;
        int rightchild = i*2+2;
        int maxindex = i;
        if (leftchild < n && a[leftchild] > a[maxindex] ) {
            maxindex = leftchild;
        }
        if (rightchild < n && a[rightchild] > a[maxindex]) {
            maxindex = rightchild;
        }
        if (maxindex != i) {
            int tmp = a[maxindex];
            a[maxindex] = a[i];
            a[i] = tmp;
            heapify(a, n, maxindex);
        }
    }
    private static void build_heap(int a[], int n){
        int last_parent = (n-1-1)/2;
        for (int i = last_parent; i >= 0; i--) {
            heapify(a, n, i);
        }
    }
}
1 2 3 3 4 4 5 6 7 8 9 9 20 23 34 45 90 190 345 546 9087 23465 

C/C++

  void swap(int *a, int *b){
    int tmp = *a;
    *a = *b;
    *b = tmp;
  }
  void heapify(int A[], int N, int i){
    int leftchild = i*2+1;
    int rightchild = i*2+2;
    int maxindex = i;
    if (leftchild < N && A[leftchild] > A[maxindex]) {
      maxindex = leftchild;
    }
    if (rightchild < N && A[rightchild] > A[maxindex]) {
      maxindex = rightchild;
    }
    if (maxindex != i) {
      swap(&A[maxindex], &A[i]);
      heapify(A, N, maxindex);
    }
  }

  void build_heap(int A[], int N){
    int last_parent = (N-1-1)/2;
    int i;
    for (i = last_parent; i >= 0; i--) {
      heapify(A, N, i);
    }
  }

int main(int argc, char *argv[])
{
  int A[] = {2, 1, 3, 4, 5, 3, 6, 7, 8, 4, 9, 45, 9,34, 23,345, 546,20, 23465, 90, 190};
  int N = sizeof(A)/sizeof(int);
  build_heap(A, N);
  for (int i = N-1; i >= 0; i--) {
    swap(&A[i], &A[0]);
    heapify(A, i, 0);
  }

  for (int j = 0; j < N; ++j) {
    printf("%d ",A[j]);
  }
  return 0;
}


1 2 3 3 4 4 5 6 7 8 9 9 20 23 34 45 90 190 345 546 23465

Typescript

swap in-place

// let swap = function (left:number, right:number){
//       var temp = left
//       left = right
//       right = temp
//   }

let heapfly =  function(list:number[], length:number, index:number){
      var leftchild = index*2+1
      var rightchild = index*2+2
      var maxindex = index
      if (leftchild < length && list[leftchild] >list[maxindex]) {
          let temp = leftchild
          leftchild = maxindex
          maxindex = temp
//          swap(leftchild, minindex)
      }

    if (rightchild < length && list[rightchild]>list[maxindex]) {
        let tmp = rightchild
        rightchild = maxindex
        maxindex = tmp
        //  swap(leftchild, minindex)
      }
      if (maxindex != index) {
          let tp = list[maxindex]
          list[maxindex] = list[index]
          list[index] = tp
          heapfly(list, length, maxindex)
      }
  }

 let build_heap = function (list:number[], lenght:number){
      var lastperent = Math.floor((length-1-1) / 2);
      for (var i = lastperent; i >= 0; i--) {
          heapfly(list, length, i);
      }
  }

  var list: number[] = [2, 1, 3, 4, 5, 3, 5, 7, 8, 45,  9, 25, 34, 23, 345, 546, 20, 23465, 90, 19];
  console.log(list)
  var length: number = list.length;
  build_heap(list, length)

  for (var i = length-1; i >= 0; i--) {
      let temp = list[i]
      list[i] = list[0]
      list[0] = temp
      heapfly(list, i, 0)
  }

  console.log(list)

swap in function

let swap = function (left:number, right:number){
  return [right, left]
  }

let heapfly =  function(list:number[], length:number, index:number){
      var leftchild = index*2+1
      var rightchild = index*2+2
      var maxindex = index
      if (leftchild < length && list[leftchild] >list[maxindex]) {
          [leftchild, maxindex] = swap(leftchild, maxindex)
      }

    if (rightchild < length && list[rightchild]>list[maxindex]) {
        [rightchild, maxindex] = swap(rightchild, maxindex)
      }
      if (maxindex != index) {
          [list[maxindex], list[index]] = swap(list[maxindex], list[index])
          heapfly(list, length, maxindex)
      }
  }
 let build_heap = function (list:number[], lenght:number){
      var lastperent = Math.floor((length-1-1) / 2);
      for (var i = lastperent; i >= 0; i--) {
          heapfly(list, length, i);
      }
  }
  var list: number[] = [2, 1, 3, 4, 5, 3, 5, 7, 8, 45,  9, 25, 34, 23, 345, 546, 20, 23465, 90, 19];
  console.log(list)
  var length: number = list.length;
  build_heap(list, length)

  for (var i = length-1; i >= 0; i--) {
      [list[i], list[0]]= swap(list[i], list[0])
      heapfly(list, i, 0)
  }
  console.log(list)

[
    2,  1,     3,  4,   5,
    3,  5,     7,  8,  45,
    9, 25,    34, 23, 345,
  546, 20, 23465, 90,  19
]
[
   1,  2,   3,   3,     4,
   5,  5,   7,   8,     9,
  19, 20,  23,  25,    34,
  45, 90, 345, 546, 23465
]

Shell Sort

Algorithm

A[a] for a -> 0, 1, 2....l-1
for G[g] for g -> 0, 1, ...m
for j -> 0, 1, 2...m-1:
  d = G[j]
  for i -> d, 2d, 3d   
    value <- A[i]
    index <- i
    while(A[index-d] > value && index > 0)
        A[index] = A[index-d]
        index -= d        
    A[index] <- value

Python

def shellsort(list1, N):
    G = [7, 5, 3, 1]
    for d in G:
        i = d
        while i < N:
            value = list1[i]
            index = i
            while index > 0 and list1[index-d] > value:
                list1[index] = list1[index-d]
                index -= d
            i += d
            list1[index] = value

list1 = [2, 1, 3, 4, 5, 3, 5, 7, 8, 45,  9, 25, 34, 23, 345, 546, 20, 23465, 90, 19, 900]
langdu = len(list1)
shellsort(list1, langdu)
print(list1)
[1, 2, 3, 3, 4, 5, 5, 7, 8, 9, 19, 20, 23, 25, 34, 45, 90, 345, 546, 900, 23465]

Java

class ShellSorting
{
    public static void main(String[] args)
    {
        int a [] = {2, 1, 3, 4, 5, 3, 6, 7, 8, 4, 9, 45, 9,34, 23,345, 546,20, 23465, 90, 19};
        int langdu = a.length;
        shellsort(a, langdu);
        for (int i = 0; i < langdu; i++) {
            System.out.printf("%d ", a[i]);
        }
    }
    private static void shellsort(int []A, int N){
        int Grap [] = {7, 5, 3, 1};
        for (int i = 0; i < Grap.length; i++) {
            int d = Grap[i];
            for (int j = d; j < N; j+=d) {
                int value = A[j];
                int index = j;
                while(index > 0 && A[index-d] > value){
                    A[index] = A[index-d];
                    index -= d;
                }
                A[index] = value;
            }
        }
    }
}

1 2 3 3 4 4 5 6 7 8 9 9 19 20 23 34 45 90 345 546 23465 

C/C++

int main(int argc, char *argv[])
{
  int A[] = {2, 1, 3, 4, 5, 3, 6, 7, 8, 4, 9, 45, 9,34, 23,345, 546,20, 23465, 90, 19, 23, 45,78};
  int langdu = sizeof(A)/sizeof(int);
  shellsort(A, langdu);
  for (int i = 0; i < langdu; ++i) {
    printf("%d ",A[i] );
  }
  return 0;
}
void shellsort(int A[], int langdu){
  int grap[] ={7, 5, 3, 1};
  int N = sizeof(grap) / sizeof(int);
  for (int j = 0; j < N; ++j) {
    int d = grap[j];
    for (int i = d; i < langdu; i=i+d) {
      int value = A[i];
      int index = i;
      while (index > 0 && A[index-d] > value) {
        A[index] = A[index-d];
        index -= d;
      }
      A[index] = value;
    }
  }
  return;
}

1 2 3 3 4 4 5 6 7 8 9 9 19 20 23 23 34 45 45 78 90 345 546 23465

Redix

Description

N numbers are waiting to be sorted,
each number has maxmum d digit,
and each digit is from 0 to k

Algorithmu

Least significant digital OR Most significant digital

LSD: from right to left, only sort all numbers according to the last digit(better with conut sort)
and then move  to left on the second digit, do it again
Time complexity  <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord">Θ</span><span class="mopen">(</span><span class="mord mathnormal">d</span><span class="mopen">(</span><span class="mord mathnormal">n</span><span class="mspace" style="margin-right:0.2222em;"></span><span class="mbin">+</span><span class="mspace" style="margin-right:0.2222em;"></span></span><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord mathnormal" style="margin-right:0.03148em;">k</span><span class="mclose">))</span></span></span></span>

Bucket Sort

Algorithm

all data are uniformly distributed in a range
spilt the range into n equal-sized intervals
independently chosen data and put them into corresponding interval
sort each interval(better with insert sort)
output by list in order of all buckets

Count Sort

Algorithm

A[n] for n from 1 to N will be sorted
using additional array C[k]
where k from min(A) to max(A)
output B[n] for n from 1 to N

for i from 1 to n: C[i] <- 0
for n from 1 to N: C[A[n]]++
for i from 2 to n: C[i] = C[i]+C[i-1]
for n from N to 1: B[C[A[n]]] = A[n], C[A[n]]--

Python

A = [1,4,2,5,3,6,2,5,3,6,3,4,7,8,4]
print(A)
lengthA = len(A)
minA = min(A)
maxA = max(A)
lengthC = maxA-minA+1

C = [0]*lengthC

for n in range(lengthA):
  C[A[n]-1] = C[A[n]-1]+1
print(C)

for i in range(1, lengthC,1):
  C[i] = C[i]+C[i-1]
print(C)

B = [0]*lengthA
for n in range(lengthA-1,-1,-1):
  B[C[A[n]-1]-1] = A[n]
  C[A[n]-1] = C[A[n]-1]-1

print(B)


[1, 4, 2, 5, 3, 6, 2, 5, 3, 6, 3, 4, 7, 8, 4]
[1, 2, 3, 3, 2, 2, 1, 1]
[1, 3, 6, 9, 11, 13, 14, 15]
[1, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 6, 6, 7, 8]

Dichotomy

C/C++

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int dichotomy(int **p, int *start, int *end, int x){
  if (*p == NULL) {
    printf(" This array is empty !\n");
    return -1;
  }
  if (x < *start || x > *end) {
    printf("this element is not in the array\n");
    return -1;
  }
  if (x == *start || x == *end) {
    return x;
  }
  int len = 0;
  for (int *temp = *p; *temp != *end; temp++) {
    len++;
  }

  int mid = *(*p+len/2);
  if (mid == *start || x == *end) {
    return -1;
  }

  if (mid >= x) {
    return dichotomy(p, start, &mid, x);
  }else {
    int * newp = *p+len/2;
    return dichotomy(&newp, &mid, end, x);
  }
}

int main(int argc, char *argv[])
{
  int array[] = {1,3,7,12,45,78,234,678,5678};
  int x = 690;
  int *p = array;
  int *start = array;
  int *end1 = &array[8];
  int *end = (int *)(&array+1);
  int a = dichotomy(&p, start, (end-1), x);
  if (a == x) {
      printf("the element is found !\n");
  }else {
      printf("the element is not found !\n");
  }
  return 0;
}


Using (int *)(&list+1)-1 to find the last elemenet of list[]

#include <stdio.h>
int isinarray(int **p, int *start, int *end, int x){
  if (*p == NULL) {
    return 0;
  }
  if (x < *start || x > *end) {
    return 0;
  }

  if (x == *start || x == *end) {
    return 1;
  }

  int i = 0;
  for (int *temp = *p; *temp != *end; temp++) {
    i++;
  }
  if (i == 1 && (x != *start || x != *end)) {
    return 0;
  }

  int medium = *(*p+i/2);
  if (medium >= x) {
    return isinarray(p, start, &medium, x);
  }else {
    int *m = *p+i/2;
    return isinarray(&m, &medium, end , x);
  }
}


int main(int argc, char *argv[])
{
  int list [] = {1,3,6,9,12,34,56,78,90,123,456,789};
  int *p = list;
  int x = 39;
  if (isinarray(&p, list, (int *)(&list+1)-1, x)) {
    printf("IN");
  }else {
    printf("NOT IN");
  }
  return 0;
}

NOT IN

Stupidmax

  #include <stdio.h>
#include <math.h>
#define N 5

int Mdiff(int a[N][N]){
  int myglobaldiff = 0;
  int mylocaldiff = 0;
  int mylocaldiff_tmp = 0;
  int diff = 0;
  for (int x = 0; x < N; x++) {
    for (int i = 0; i < N; ++i) {
      mylocaldiff_tmp = a[x][i]-a[x][i];
      for (int y = 0; y < N; y++) {
    diff = fabs(a[x][i] - a[x][y+i]);
    if (y+i < N && diff > mylocaldiff_tmp){
      mylocaldiff_tmp = diff;
    }
      }
      if (mylocaldiff_tmp > mylocaldiff){
    mylocaldiff =  mylocaldiff_tmp;
      }
    }
    if (mylocaldiff > myglobaldiff){
      myglobaldiff = mylocaldiff;
    }
  }
  return myglobaldiff;
}


int main(int argc, char *argv[])
{

  int a [5][5] = {
    {
      1,2,3,4,52220
    },
    {
      3,4,62,56,2
    },
    {
      3,4,62,56,82
    },
    {
      10,20,62,56,2220,
    },
    {
      3,4,62,56,29
    }
  };
  int tmpmax = Mdiff(a);
  printf("%d", tmpmax);
  return 0;
}


HoffmannCode

C/C++

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
  int data;
  int parent, lboy, rboy;
}HTNode, *HoffmanTree;
typedef char ** HoffmanCode;
void Select(HoffmanTree HT, int *s1, int *s2, int end){
  int min1, min2;
  int i = 1;
  while (HT[i].parent != 0 && i <= end) {
    i++;
  }
  min1 =  HT[i].data;
  *s1 = i;
  i++;
  while (HT[i].parent != 0 && i <= end) {
    i++;
  }
  if (HT[i].data <= min1) {
    min2 = min1;
    *s2 = *s1;
    min1 = HT[i].data;
    *s1 = i;
  }else {
    min2 = HT[i].data;
    *s2 = i;
  }
  for (int j = i+1; j <= end; j++) {
    if (HT[j].parent != 0) {
      continue;
    }
    if (HT[j].data <= min1) {
      min2 = min1;
      *s2 = *s1;
      min1 = HT[j].data;
      *s1 = j;
    }else {
      min1 = HT[j].data;
      *s2 = j;
    }
  }
}


void CreateHoffman(HoffmanTree *HT, int *list, int length){
  if (length <= 1) {
    return;
  }
  int m = 2*length-1;
  *HT = (HoffmanTree)malloc(sizeof(HTNode) * m);
  int i;
  for (i = 1; i <= length; i++) {
    (*HT+i)->data = *(list+i-1);
    (*HT+i)->parent = 0;
    (*HT+i)->lboy = 0;
    (*HT+i)->rboy = 0;
  }
  for (i = length+1; i <= m; i++) {
    (*HT+i)->data = 0;
    (*HT+i)->parent = 0;
    (*HT+i)->lboy = 0;
    (*HT+i)->rboy = 0;
  }

  for (i = length+1; i <=m; i++) {
      int s1, s2;
      Select(*HT, &s1, &s2, i-1);
      (*HT)[s1].parent = (*HT)[s2].parent = i;
      (*HT)[i].lboy = s1;
      (*HT)[i].rboy = s2;
      (*HT)[i].data = (*HT)[s1].data + (*HT)[s2].data;
  }
}

void CreateHoffmanCode(HoffmanCode *hcode, HoffmanTree HT, int length){
  *hcode = (HoffmanCode)malloc(sizeof(char * ) * length+1);
  char *cd = (char *)malloc(sizeof(char) * length);
  cd[length-1] = '\n';
  for (int i  = 1; i <= length; i++) {
    int start = length -1;
    int c = i;
    int j = HT[c].parent;
    while (j != 0) {
      if (HT[j].lboy == c) {
    cd[--start] = '1';
      }
      else {
    cd[--start] = '0';
      }
      c = j;
      j = HT[j].parent;
    }
    (*hcode)[i] = (char *)malloc(sizeof(char )*length-start);
    strcpy((*hcode)[i], &cd[start]);
  }
  free(cd);
}
void showHoffmanCode(HoffmanCode hcode, int *list, int length){
  printf("Here we go\n");
  for (int i = 1; i <= length; i++) {
    printf("%d : is %s\n",list[i-1], hcode[i]);
  }
}

int main(int argc, char *argv[])
{
  HoffmanTree htree;
  HoffmanCode hcode;
  int list[] = {1,18,2,56,3,4, 44,5,7,34,78,90,234,789};
  int length = sizeof(list)/sizeof(int);
  CreateHoffman(&htree, list, length);
  CreateHoffmanCode(&hcode, htree, length);
  showHoffmanCode(hcode, list, length);
  return 0;
}


Here we go
1 : is 0000001

18 : is 00001

2 : is 000001

56 : is 0001

3 : is 0000000001

4 : is 000000001

44 : is 00000001

5 : is 0000000000001

7 : is 000000000001

34 : is 00000000001

78 : is 001

90 : is 01

234 : is 0

789 : is 0000000000000

JosephusRing

C/C++

#+header: :var n = 20 :var k = 1 :var m = 5
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
  int number;
  struct node * next;
}person;
person * initLink(int n){
  person * head=(person*)malloc(sizeof(person));
  head->number=1;
  head->next=NULL;
  person * cyclic=head;
  for (int i=2; i<=n; i++) {
    person * body=(person*)malloc(sizeof(person));
    body->number=i;
    body->next=NULL; 
    cyclic->next=body;
    cyclic=cyclic->next;
  }
  cyclic->next=head;//首尾相连
  return head;
}

void findAndKillK(person * head,int k,int m){

  person * tail=head;
  //找到链表第一个结点的上一个结点,为删除操作做准备
  while (tail->next!=head) {
    tail=tail->next;
  }
  person * p=head;
  //找到编号为k的人
  while (p->number!=k) {
    tail=p;
    p=p->next;
  }
  //从编号为k的人开始,只有符合p->next==p时,说明链表中除了p结点,所有编号都出列了,
  while (p->next!=p) {
    //找到从p报数1开始,报m的人,并且还要知道数m-1de人的位置tail,方便做删除操作。
    for (int i=1; i<m; i++) {
      tail=p;
      p=p->next;
    }
    tail->next=p->next;//从链表上将p结点摘下来
    printf("出列人的编号为:%d\n",p->number);
    free(p);
    p=tail->next;//继续使用p指针指向出列编号的下一个编号,游戏继续
  }
  printf("出列人的编号为:%d\n",p->number);
  free(p);
}

int main() {
  printf("输入圆桌上的人数n:");
  /* int n; */
  /* scanf("%d",&n); */
  person * head=initLink(n);
  printf("从第k人开始报数(k>1且k<%d):",n);
  /* int k; */
  /* scanf("%d",&k); */
  printf("数到m的人出列:");
  /* int m; */
  /* scanf("%d",&m); */
  findAndKillK(head, k, m);
  return 0;
}

KMPmachting

C/C++

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void genertarray(char pattern[], int prefix[], int n){
  prefix[0] = 0;
  int len = 0;
  int i =1;
  while (i < n) {
    if (pattern[i] == pattern[len]) {
      len++;
      prefix[i] = len;
      i++;
    }else {
      if (len > 0) {
    len = prefix[len-1];   //go the preious len, and matching again
      }else {
    prefix[i] = len;        // in case len <= 0, bzw, the first and second is not matching
    i++;
      }
    }
  }
}

void move_array(int prefix [], int n){
  int i;
  for ( i = n-1; i > 0; i--) {
    prefix[i] = prefix[i-1];
  }
  prefix[0] = -1;
}

void kmp_search(char text[], char pattern[]){
  int k = strlen(pattern);
  int* prefix =(int *) (malloc(sizeof(int )* k));
  genertarray(pattern, prefix, k);
  move_array(prefix, k);

  // text    index i, max n
  // pattern index j, max m

  int i = 0; int j = 0;
  int n = strlen(text);
  int m = strlen(pattern);
  while (i < n) {
    if (j == m-1 && text[i] == pattern[j]) { // if found
      printf("Fonund at %d \n", i-j);
      j = prefix[j];                         // still go forward
    }
    if (text[i] == pattern[j]) {            
      i++;j++;
    }else {
      j = prefix[j];                        //if not matching
      if (j == -1) {                        //if the first is not matching
    i++;j++;
      }
    }
  }
}

int main(int argc, char *argv[])
{
  char pattern[] = "ABABBBA"; 
  char text[]    = "JUHkSABABBBABABA";
  kmp_search(text, pattern);
  return 0;
}

Fonund at 5

C/C++

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

//sort only the pure given numbers, and change each time the sort direction
int recSort(int *start, int *end, int reverse){
  int count = 0;

  if (start == NULL || end == NULL) {
    return 0;
  }

  if (start == end || start +1 == end) {
    return 0;
  }


  int* p;
  if (reverse) 
    p = end -1;
  else
    p = start+1;


  while (p < end && p > start ) {
    if (*(p-1) < *p) {
      int temp = *(p-1);
      *(p-1) = *p;
      *p = temp;
      count++;
    }

    if (reverse)
      p--;
    else
      p++;
  }

  if (reverse)
    return count +  recSort(start+1, end, 0);
  else
    return count +  recSort(start, end-1, 1);

}


int main(int argc, char *argv[]) {

  if (argc < 1) {
    recSort(NULL, NULL, 0);
    return -2;
  }

  int* f = malloc(sizeof(int) * (argc-1));
  if (f == NULL) {
    return -3;
  }

  for (int i = 1; i < argc; i++) {
    f[i-1] =atoi(argv[i]);
  }

  printf("before the sort \n");
  for (int i =1 ; i < argc; i++) {
    printf("%d\n",f[i-1]);
  }

  int i=  recSort(f, &f[argc-1] , 0);
  printf("alles in allem, %d times change  \n",i);

  printf("after the sort \n");
  for (int i =1 ; i < argc; i++) {
    printf("%d\n",f[i-1]);
 }


  free(f);
  return 0;
}


Longest Substring Without Repeating Characters

python

class Solution:
    def lengthOfLongestSubstring(self, s):
        hashmap = {}
        lastindex = 0
        maxlen = 0
        for i in range(len(s)):
            if s[i] in hashmap:
                lastindex = max(lastindex, hashmap[s[i]]+1)
            maxlen = max(maxlen, i-lastindex+1)
            hashmap[s[i]] = i
        return maxlen

ss = Solution()

print(ss.lengthOfLongestSubstring("abcabcbb"))
print(ss.lengthOfLongestSubstring("abcdefkj"))
print(ss.lengthOfLongestSubstring("abc"))
print(ss.lengthOfLongestSubstring("pwwkew"))
print(ss.lengthOfLongestSubstring("abb"))
print(ss.lengthOfLongestSubstring("abba"))
3
8
3
3
2
2

k-way Merge

description

L1, L2...Lk are all sorted array with n elements, will be mereged into one sorted array

Naive merge

merge L1 with L2 get l2
merge l2 with L3 get l3
...
Time Compexity <span class="katex-display"><span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord">Θ</span><span class="mopen">(</span><span class="mord mathnormal">n</span><span class="mspace" style="margin-right:0.2222em;"></span><span class="mbin">⋅</span><span class="mspace" style="margin-right:0.2222em;"></span></span><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord mathnormal" style="margin-right:0.01968em;">l</span><span class="mord mathnormal">o</span><span class="mord mathnormal" style="margin-right:0.03588em;">g</span><span class="mord mathnormal" style="margin-right:0.03148em;">k</span><span class="mclose">)</span></span></span></span></span>

rund merge

L1 with L2 for l2
L3 with L4 for l4
...
L2 with L4 for l4
...

Heap merge

build a heap with k element, which are from each array L, extract Max-Heap, and rebuild the Heap, in removed array L with new (next) element

Dynamic program

Description

变量类型, 坐标, 限标 都可以是一维或者多维 在状态转移函数中自己影响自己

Maximum subarray

A1. Erschöpfende Suche/ Brute-Force-Suche/ Exhaustive Search


A2. Zwischen Prozessen mehr anwenden A3. Rekursive A4. Max Maxsuffix

blunt force

A[a] for = 0 to n-1
max -> -Infty
for i = 1 to n
  for j = i to n
    for k = i to j
      sum = sum+A[k]
    if sum > max:
      max = sum
return max

iterative based

A[a] for a = 0 to n-1
max = -Infty
for i = 1 to n:
  sum = 0
  for j = i to n:
    sum = sum + A[j]
  if sum > max:
    max = sum
return max

dynamic programmierung

A[a] for a = 0 to n-1
max = - Infty
init array S with n elemenets 0
S[0] = A[0]
for i = 1 to n-1:
  S[i] = max{S[i-1]+A[i], A[i]}
  if S[i] > max:
    max = S[i]
return max

Algorithm

A[a] for a = 0 to n-1
max = 0
Stmp = 0
for i = 1 to n-1:
  Stmp = max{Stmp+A[i], A[i]}
  if Stmp > max:
    max = Stmp
return max

C/C++

int main(int argc, char *argv[])
{
  int MaxSubArray(int A[], int N){
    int i, b = 0, maxsum = 0;
    for (i = 0; i < N; ++i) {
      if (b > 0) {
        b += A[i];
      }else{
        b = A[i];
      }
      if (b > maxsum) {
        maxsum = b;
      }
    }
    return maxsum;
  }

  int A[] = {2, 1, 3, 4, 5, 3, 6, 7, 8, 4, 9, 45, 9,34, 23,345, 546,20, 23465, 90, 19, 23, 45,78};
  int length = sizeof(A)/sizeof(int);
  int max = MaxSubArray(A, length);
  printf("%d \n",max);
  return 0;
}

24794

maximum submatrix

Brute force solution

list all submatrix,
sum = 0 
for xstart -> 0,1...l:
    for xstop -> xstart+1, xstart+2...l:
        for ystart -> 0, 1, 2....l:
            for ystop -> ystart+1, ystart+2...l:
                for x -> xstart .... xstop:
                    for y -> ystart .... ystop:
                       sumsub += A[x][y]
                if sumsub > sum:
                   sum = sumsub
import random
import numpy
def maxsublist(arr, n):
    b = 0
    sumlist = 0
    for j in range(n):
        if b > 0:
            b += arr[j]
        else:
            b = arr[j]
        if b > sumlist:
            sumlist = b
    return sumlist


def maxsubmatrix(A, l):
    Acolmun = np.zeros(l)
    summaxtrix = 0
    for i in range(l):
        if summaxtrix > 0:
            Acolmun += A[i,:]
            sumlist = maxsublist(Acolmun, l)
            print(Acolmun)
            print("the maximum sublist is: {}".format(sumlist))
            print("the maximum submatrix is: {}".format(summaxtrix))
        else:
            Acolmun = A[i,:]
            sumlist = maxsublist(Acolmun, l)
            print(Acolmun)
            print("the maximum sublist is: {}".format(sumlist))
            print("the maximum submatrix is: {}".format(summaxtrix))
        if sumlist > summaxtrix:
            summaxtrix = sumlist
    return summaxtrix

import random
l = 8
a = [[]]*l
gsm = [[]]*l
#initialization a random matrix with shape of 8x8
for i in range(l):
    a[i] = [random.randint(-5, 5) for x in range(l)]

print("Original random matrix  \n")
a = np.array(a)
print(a)
max = 0
for i in range(1, l):
    for xstart in range(i-1, l):                            # x start  of submatrix
        for xstop in range(i+xstart, l+1-i+1):              # x stop    of submatrix
            for j in range(1, l):
                for ystart in range(j-1, l):                 # y start of submatrix
                    for ystop in range(j+ystart, l+1-j+1):   # y stop of submatrix
                        lip = [[] for x in range(l)]
                        count = 0
                        for x in range(xstart, xstop):
                            for y in range(ystart, ystop):
                                lip[x].append(a[x][y])
                                count += a[x][y]
                        # if (xstart ==6 and xstop == 8 and ystart == 6 and ystop == 8): #test small submatrix
                        #     print (count);

                        if count > max:
                            lipmax = [[] for x in range(l)]
                            max = count
                            lipmax = lip
print("maximux submatrix :\n")
lipmax = np.array(lipmax)
for i in range(len(lipmax)):
    print("\n")
    for j in lipmax[i]:
        print("{:>4d}".format(j), end="")

print("\n")
print("The summary is ", max)
print("with dynamic programmierung is {}".format(maxsubmatrix(a, l)))

dynamic programmierung

import random
import numpy as np

def maxsublist(arr, n):
    b = 0
    sumlist = 0
    for j in range(n):
        if b > 0:
            b += arr[j]
        else:
            b = arr[j]
        if b > sumlist:
            sumlist = b
    return sumlist

def maxsubmatrix(A, l):
    Acolmun = np.zeros(l)
    summaxtrix = 0
    for i in range(l):
        if summaxtrix > 0:
            Acolmun += A[i,:]
            sumlist = maxsublist(Acolmun, l)
        else:
            Acolmun = A[i,:]
            sumlist = maxsublist(Acolmun, l)
        if sumlist > summaxtrix:
            summaxtrix = sumlist
    return summaxtrix
l = 8
A = [[]]*l
for i in range(l):
    A[i] = [random.randint(-5, 5) for x in range(l)]
A = np.array(A)
print(A)
print(maxsubmatrix(A, l))    
[[ 5 -2  3  4 -1  4 -3  4]
 [ 2 -1  1 -2 -1  2 -4 -5]
 [ 2 -4  0  5 -4  5  3  4]
 [ 3 -5 -2 -2  1 -4  4 -3]
 [ 5 -2  5  4 -2  4 -3  0]
 [ 5 -2  0  4 -4 -1  3  4]
 [-3 -4 -3  1  1 -3 -5  4]
 [ 4  3  5 -5  0 -3 -2  0]]
29

Find the sum of a specific value in a list

在一个列表中找到一个特定数值的和

Python

with recursive

 arr = [3, 34, 4, 12, 5, 2]
 def res_subset(arr, i, s):
     if s == 0:
         return True
     elif i == 0:
         return arr[0] == s
     elif arr[i] > s:
         return res_subset(arr, i-1, s)
     else:
         A = res_subset(arr, i-1, s-arr[i])
         B = res_subset(arr, i-1, s)
         return A or B
print(res_subset(arr, len(arr)-1, 9))
print(res_subset(arr, len(arr)-1, 10))
print(res_subset(arr, len(arr)-1, 11))
print(res_subset(arr, len(arr)-1, 12))
print(res_subset(arr, len(arr)-1, 13))

True
True
True
True
False

without rekursive

import numpy as np
arr = [3, 34, 4, 12, 5, 2]
target = 13
result = np.zeros((len(arr), target+1), dtype = bool)
result[: , 0] = True
result[0 , :] = False
result[0 , arr[0]] = True
for i in range(1, len(arr)):
    for j in range(1, target+1):
        if arr[i] > j:
            result[i, j] = result[i-1, j]
        else:
            A = result[i-1, j-arr[i]]
            B = result[i-1, j]
            result[i, j] = A or B
print(result[-1][-1])            

False

Langest increasing subsequence (LIS)

Python

list1 = [2, 1, 3, 45, 76, 89, 457, 54, 4, 5, 3, 6, 7, 8, 4, 9]
l = len(list1)
a = [1]*l
b = [[] for x in range(l)]

for i in range(l):
    for j in range(i):
        if (list1[i] > list1[j]) and (a[i] < (a[j] + 1)):
            a[i] = a[j]+1
            b[i].append(list1[j])
    b[i].append(list1[i])

print(a)
maxa = a.index(max(a))
print("the maximun length of LIS of list1 is {}".format(max(a)))
print("the LIS is {}".format(b[maxa]))

list1 = [2, 1, 3, 45, 76, 89, 457, 54, 4, 5, 3, 6, 7, 8, 4, 9]
l = len(list1)
a = [1]*l

for i in range(l):
    for j in range(i):
        if (list1[i] > list1[j]):
            a[i] = max(a[i], a[j]+1)
print(a)
print("the maximun length of LIS of list1 is {}".format(max(a)))

packsack

0-1 sack

complete sack

k is the total number, if 背包全放每一种时的最大份数

bund sack

n is the bunded number for each variante

Order Statistics

description

For Array a[i], i from 0 to n-1
we want to find the the k-th biggest element in linear time
1-th biggest is the minimun
n-1-th biggest is the maximum

for minimun and maximum

normal iterative: need 2n-2, each n-1 2 terms iterative:

(min_1, max_1) <- (a[0],a[1])
(min_2, max_2) <- (a[2],a[3])
(min_3, max_3) <- (a[4],a[5])
...
(min_n/2, max_n/2) <- (a[n-2],a[n-1])

min = min_1, max = max_1
for i from 2 to n/2:
    if min_i < min:
        min = min_i
    if max_i > max:
        max = max_i
return min, max

linear approach

index: i


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24


array a[]:


2 14 6 27 4 67 24 9 16 45 26 17 20 8 41 23 34 5 36 77 44 3 25 22


looking for the k-th biggest elemenet

divide array a[] into length/5 groups, each group has 5 elemenets, and the last is not required to be 5

--- --- --- --- ---


2 67 26 23 44


--- --- --- --- ---


14 24 17 34 3


--- --- --- --- ---


6 9 20 5 25


--- --- --- --- ---


27 16 8 36 22


--- --- --- --- ---


4 45 41 77


--- --- --- --- ---

sort all group with insert sorting

--- --- --- --- ---


2 9 8 5 3


--- --- --- --- ---


4 16 17 23 22


--- --- --- --- ---


6 24 20 34 25


--- --- --- --- ---


14 45 26 36 44


--- --- --- --- ---


27 67 41 77


--- --- --- --- ---

get the mediums of each group


6 24 20 34 25


if at this step, the number of elemenets are more than 5, recursive spilt again

sort group


6 20 24 25 34


get the medium 24. at spilt the array a[] with this element a[7]=24.

if k==7 return 24

if k< 7 looking for k-th biggest elemenet in


2 14 6 27 4 67


if k> 7 looking for the (k-16)-th biggest elemenet in


9 16 45 26 17 20 8 41 23 34 5 36 77 44 3 25 22


complexity

no matter for k > i (i = 7, a[7]=24), we can exculsive the black position

--- --- --- --- ---


2 8 9 3 5


--- --- --- --- ---


4 17 16 22 23


--- --- --- --- ---


6 20 24 25 34


--- --- --- --- ---


14 26 45 44 36


--- --- --- --- ---


27 41 67 77


--- --- --- --- ---

--- --- --- --- ---


                3      5

--- --- --- --- ---


                22      23

--- --- --- --- ---


                25      34

--- --- --- --- ---


14 26 45 44 36


--- --- --- --- ---


27 41 67 77


--- --- --- --- ---

elements are definitely excluded

The recursive format is

Range Minimun Query

description

array A[i] for i from 0 to n-1
given two number j, k, so 0 < i< j<n-1
return the minimun elements of range A[j]...A[k]

naiv approach

min = A[0]
for n from 0 to n-2:
  for m from 1 to n-1:
    for o from n to m:
      if A[o] < min:
        min = A[o]

obviously the time compexity is

DP naiv approach

with Dynamic Program to iterative scan.

set M[n][n] as empty matrix to save RMQ of array A[n].
M[i][i] = A[i]
for i from 0 to n-2:
  M[i][j] = A[i]        if A[i] < M[i-1][j]
          = M[i-1][j]   otherwise
  for j from 1 to n-1:
    M[i][j] = A[j]        if A[j] < M[i][j-1]
            = M[i][j-1]   otherwise

obviously the time compexity is

addation M approach

set K=ceiling ()

set M´[i][k] = RMQ(i, i+2^k^-1)

---o-------------------oo------------------------o------

---+i

-----------------------+

------------------------+

--------------------------------------------------+

M´[*][1] = RMQ(i, i+1)
for i from 0 to n-1:
  for k from 2 to K:
    M´[i][k] = M´[i][k-1]           if A[M´[i][k-1]] < A[M´[i+2^{k-1}][k-1]] 
             = M´[i+2^{k-1}][k-1]   otherwise

get RMQ(i,j)

s = floor(log^j-i^)

---o------------0-------o------------------------o------

---i

----------------j-2^s^+1

------------------------i+2^s^-1

-------------------------------------------------j

for i to i+2^s-1: M´[i][s]
for j-2^s-1 to j: M´[j-2^s-1][s]
RMQ(i,j)= A[M´[i][s]]      if  A[M´[i][s]] < A[M´[j-2^s-1][s]]
        = M´[j-2^s-1][s]   otherwise

the time compexity is

partional approach

Array A[n]



spilt Array A into block size of we have n/s blocks

--------+ --------+ --------+ --------+ --------+



--------+ --------+ --------+ --------+ --------+

we build 2 array h[n/s] and pos[n/s] h[n/s]: contains the minimum element of each block



pos[n/s]: contains the position of the corresponding elements in h when it is still in A.



For RMQ(i, j)
i´ = i/s+1
j´ = j/s
l = RMQ_h(i´, j´)
pos[l] = RMQ(i´s, j´s-1)

but the RMQ can still be in [i...i´s] or [j´s...j]
so l´ = RMQ[i, i´s] and
l´´ = RMQ[j´s, j]
return min(l, l´, l´´)

Now comes the question, how to get l´ and l´´ in constant time (in a block)? this can only be solved in special situation

()RMQ

it called Normalisation.

normalise all block (x,[....]) to (0,x) where

for one block, there are permutation of -1 and +1,

this have time compexity

and we compute all permutation probability into a sxs matrix.

for all RMQ query in this block can be saved in this matrix.

this have time compexity of

all together we habe

oooo--------ooooo--------ooooo-----ooooo------oooooo------ooooooo



(0, ) (0,) (0, ) (0,) m_x_{1} M_x_{1}

(0,x) normalisation : performance : sxs matrix for permutation

for query of RMQ in a block, auch as for l´ = RMQ[i, i´s], we find the representation of i, i´s in , we can get the corresponding RMQ

()RMQ for LCA in rooted tree

for a rooted tree, we want to find the Lowest Common Ancestor.
for two node u and v, we want to find the common ancestor of u and v
and most far away from its root.

for the rooted tree, we do the preprcess to get the following 3 array
E[*] (Euler tour) list all the node in tree with DFS, (2n-1) elements
L[*] the level of each element in E, this comply with the <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6667em;vertical-align:-0.0833em;"></span><span class="mord">±</span></span></span></span>1 property
R[*] each element position when they are first time occur in E R[i]= min(E[j]=i|1<j<2n)

find the u and v in R,
in R get the corresponding positions in E, get the range from u position to v position
find the min in L with the same range  we get in E, and return the position of minimum in L
get the LCA in E with the position we get in L

LCA(u, v) -> RMQ~L~(E[R[u]], E[R[v]])

Cartesian tree

this tree has two property,
1, it's a heap, which mean, the parents are all smaller than their childen
2, we can get the original array with the IN-order scan of the tree

How to build cartesian tree
for inserting a new node, we compare it to the root and the rightest edge,
if it is smaller than the root, trun the all(include the root) to be new node's left child
if it is bigger, go down to the next node, if go to the leaf, add it just as right child
if it is bigger, go down to the next node, if it is smaller than one node,
                                           trun all to be the left child, and new node as right chilc

this can be done in time compexity

LCA and RMQ

where is the cartesian tree of A the root of subtree, which contains i and j, is the RMQ(i,j)

Computional Geometry

Convex combinations

all points p(x, y) between and , x1< x < x2 and y1 < y < y2

Cross Product

cross Product = (sign) * (Aera of Parallelogram)

sign is +: p1 is clockweise from p2 with respect of their common origin, from p1 to (p2-p1) trun to right sign is -: p1 is connterclockweise from p2 with respect of their common origin, from p1 to (p2-p1) trun to left

Application of intersection

Direction: On-Segment: if one end-point of one Segment is convex combinations of the other Segment

Algorithm: first check if two segments straddles, and else if any d = 0, check if On-segment otherwise return No

Application of Polar Angle

the sign is positive, p1 to p2 have right trun,

The Polar Angle is p1 < p2

Sweeping

Check if any two Segments intersect in a Segments Set

sort endpoints of the segments in S from left to right, breaking ties by putting left endpoints before right endpoints, and then by y -coordinates.

T = ∅;
for each point p in the sorted list of endpoints:
    if p is the left endpoint of a segment s
        Insert(s, T )
        if (Above(s, T ) exists and intersects s) or  (Below(s, T ) exists and intersects s)
            return TRUE

    if p is the right endpoint of a segment s
        if both Above(s, T ) and Below(s, T ) exist and Above(s, T ) and Below(s, T ) intersect
            return TRUE

     Delete(s, T )
return FALSE

Convex Hull

For a Set of points <p0...pn>, we want to find the small Hull, to cover all points.

Graham's Scan

let p0 is the smallest y value in set, and Sorted all other points counterclockweise with their polar angle:

let S = empty stack
push (p0, S), Push(p1, S), Push(p2, S)
for i from 3 to n:
    while from nextTop(S), Top(S) to pi trun left:
        pop (S)
    push(pi)
return S

This take

Jarvis's march

We roll the Paper until we find the point with smallest polar angle, Build a Sequence H, start with p0 just like in Graham's Scan(with smallest y value in Set

start with p0, find the next vertex p1 with smallest polar angle with respect to p0
start with p1, find the next vertex p2 with smallest polar angle with respect to p1
start with p2, find the next vertex p3 with smallest polar angle with respect to p2
...
when we reach the highest y-value vertex,left chain is finished, start to right chain,
But from the negative x-axis, until we come back to p0

This take


title: DataStructure

#+STARTUP: overview

Stack with Array

Java

build a Stack from Array, and fulfil its methods, remember, it is METHODS One example of its porperties: decimal to binary convertion

function StackwithArray(){
    this.items = [];

    StackwithArray.prototype.push = function (value){
        this.items.push(value);
    };

    StackwithArray.prototype.pop = function(){
        return this.items.pop();
    };

    StackwithArray.prototype.peek = function(){
        return this.items[this.items.length-1];
    };
    StackwithArray.prototype.isEmpty = function(){
        return this.items.length <= 0;
    };
    StackwithArray.prototype.size = function(){
        return this.items.length;
    };
    StackwithArray.prototype.toString = function(){
        tostring = '';
        for (var i = this.items.length-1; i >= 0; i--) {
            tostring += this.items[i]+' ';
        }
        return tostring;
    };
}

var stackwithArray = new StackwithArray();
stackwithArray.push(2);
stackwithArray.push(3);
stackwithArray.push(4);
stackwithArray.push(5);
stackwithArray.push(6);
console.log(stackwithArray.toString());
console.log('Size of  stackwitharray is: '+stackwithArray.size());
stackwithArray.pop();
console.log(stackwithArray.toString());
console.log('Size of  stackwitharray is: '+stackwithArray.size());
stackwithArray.peek();
console.log(stackwithArray.toString());
console.log('Size of  stackwitharray is: '+stackwithArray.size());
console.log(stackwithArray.isEmpty());

function decimal2binary (value){
    var stack = new StackwithArray();
    while(value > 0){
        stack.push(value%2);
        value = Math.floor(value/2);
    }
    var output = '';
    while(!stack.isEmpty()){
        output += stack.pop();
    }
    return output;
};

var target = 100090; 
decimal2binary(89);
console.log(target + ' convert to binary is '+ decimal2binary(target));
6 5 4 3 2 
Size of  stackwitharray is: 5
5 4 3 2 
Size of  stackwitharray is: 4
5 4 3 2 
Size of  stackwitharray is: 4
false
100090 convert to binary is 11000011011111010

Queue with Array

JS

Queeu rebuild

build a Queue from an Array and its methods, one example is Johnausking.

function QueueWithArray(){
    this.items = [];

    QueueWithArray.prototype.enqueue = function(value){
        this.items.push(value);
    };

    QueueWithArray.prototype.dequeue = function(){
        return this.items.shift();
    };

    QueueWithArray.prototype.front = function(){
        return this.items[0];
    };

    QueueWithArray.prototype.isEmpty = function(){
        return this.items.length <= 0;
    };

    QueueWithArray.prototype.size = function(){
        return this.items.length;
    };

    QueueWithArray.prototype.toString = function(){
        var tostring = ' ';
        for (var i = this.items.length -1; i >= 0; i--) {
            tostring += this.items[i]+' ';
        };
        return tostring;
    };
}

var queue = new QueueWithArray();
queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
queue.enqueue(4);
queue.enqueue(5);
console.log(queue.toString());
queue.dequeue();
console.log(queue.toString());
queue.front();
console.log(queue.toString());
console.log(queue.isEmpty());

var personen = ['zhangsan', 'lisi', 'wangwu', 'zhaoliu', 'wuqi'];
function Johnausking(person, number){
    var queueplay = new QueueWithArray();
    for (var i = 0; i < person.length; i++) {
        queueplay.enqueue(person[i]);
    }

    while(queueplay.size() > 1){
        for (var j = 0; j <number-1; j++) {
            queueplay.enqueue(queueplay.dequeue());
        }
        queueplay.dequeue();
    }

    if (queueplay.size() == 1) {
        console.log('the left person is '+ queueplay.front());
        return person.indexOf(queueplay.front());
    }
    else
        return 'there are not only one person left';
}
console.log(Johnausking(personen, 3));
 5 4 3 2 1 
 5 4 3 2 
 5 4 3 2 
false
the left person is zhaoliu
3

Priority Queue

save all the information with priority, from small to big inner class can't use prototype

   function Priorityqueue(){
       this.array = [];
       function Node(value, priority){
           this.value = value;
           this.priority = priority;
       }

       Priorityqueue.prototype.enqueue = function(value, priority) {
           var element = new Node(value, priority);
           if (this.array.length == 0) {
               this.array.push(element);
           }else{
               var flag = false;
               for (var i = 0; i < this.array.length; i++) {
                   if (element.priority < this.array[i].priority) {
                       this.array.splice(i, 0, element);
                       flag = true;
                       break;
                   }
               }
               if (!flag) {
                   this.array.push(element);
               }
           }
       }

       Priorityqueue.prototype.dequeue = function(){
           return this.items.shift();
       };

       Priorityqueue.prototype.front = function(){
           return this.items[0];
       };

       Priorityqueue.prototype.isEmpty = function(){
           return this.items.length <= 0;
       };

       Priorityqueue.prototype.size = function(){
           return this.items.length;
       };

       Priorityqueue.prototype.toString = function(){
           var tostring = ' ';
           for (var i = this.array.length -1; i >= 0; i--) {
               tostring += this.array[i].value+':'+ this.array[i].priority+'   ';
           };
           return tostring;
       };

   }
   var priorityqueue = new Priorityqueue();
   priorityqueue.enqueue('m', 01);
   priorityqueue.enqueue('d', 59);
   priorityqueue.enqueue('l', 19);
   priorityqueue.enqueue('z', 251);
   priorityqueue.enqueue('x', 50);
   priorityqueue.enqueue('w', 504);

console.log(priorityqueue.toString());



 w:504   z:251   d:59   x:50   l:19   m:1   

Linkedlist

JS


append(elemenet) append element at the end of list insert(elemenet, position) insert elemenet at position of position update(position, elemenet) update the data to elemenet at position get(position) get the elemenet at position indexOf(elemenet) return the position of elemenet removeAt(position) remove the elemenet at position remove(elemenet) remove the elemenet no matater where it is isEmpty()
size() length of list toString()


in the update process, we have two ideas, one is normal, just change the node data the other is create a node with new data, so insert or update can be relavant

function Linkedlist()
{
    //initialization
    this.head = null;
    this.size = 0;
    function Node(data){
        this.data = data;
        this.next = null;
    }

    //append(data)
    Linkedlist.prototype.append = function(data){
        var node = new Node(data);
        var current = this.head;
        if (this.size == 0) {
            this.head = node;
        }else{
            while(current.next){
                current = current.next;
            }
            current.next = node;
        }
        this.size+= 1;
        return;
    };
    //insert(element, position)
    Linkedlist.prototype.insert = function(data, position){
        if (position < 0 || position > this.size) {
            console.log('position is not vaild');
            return;
        }
        var node = new Node(data);
        var current = this.head;
        var pervies = null;
        var tmp = 0;
        while(tmp++ < position){
            pervies = current;
            current = current.next;
        }
        node.next = current;
        pervies.next= node;
        this.size += 1;
        return;
    };

    //update(element, position)
    Linkedlist.prototype.update = function(data, position){
        if (position < 0 || position > this.size) {
            console.log('position is not vaild');
            return;
        }
        // var node = new Node(data);
        // var current = this.head;
        // var pervies = null;
        // var tmp = 0;
        // while(tmp++ < position){
        //     pervies = current;
        //     current = current.next;
        // }
        // node.next = current.next;
        // pervies.next= node;

        var current = this.head;
        var tmp = 0;
        while(tmp++ < position){
            current = current.next;
        }
        current.data = data;
    };

    //get(position)
    Linkedlist.prototype.get = function(position){
        if (position < 0 || position > this.size) {
            console.log('position is not vaild');
            return;
        }
        let current = this.head;
        let tmp = 0;
        while(tmp++ < position){
            current = current.next;
        }
        console.log('at Position of '+position+' is: '+current.data);
        return;
    };

    //indexOf(elemenet)
    Linkedlist.prototype.indexOf = function(data){
        let current = this.head;
        let tmp = 0;
        while (current){
            if (current.data == data) {
                console.log('the elemenet '+data+' is at position of '+tmp);
                return tmp ;
            }
            current = current.next;
            tmp +=1;
        };
        if (!current) {
            console.log('the elemenet '+data+' is not exist');
            return;
        }
    };

    //removeAt(position)
    Linkedlist.prototype.removeAt = function(position){
        if (position < 0 || position >= this.size) {
            console.log('position is not vaild');
            return;
        }
        if (position == 0) {
            this.head = this.head.next;
        }else{
            var index = 0;
            var current = this.head;
            var pervies = null;
            while(index++ < position){
                pervies = current;
                current = current.next;
            }
            pervies.next =  current.next;
        }

        this.size -= 1;
    };

    //remove(elemenet)
    Linkedlist.prototype.remove = function(data){
        let tmp = this.indexOf(data);
        this.removeAt(tmp);

        // var current = this.head;
        // var pervies = null;
        // while(current && current.data != data){
        //     pervies = current;
        //     current = current.next;
        // }
        // if (current) {
        //     if (current == this.head) {
        //         this.head = this.head.next;
        //     }else{
        //         pervies.next = current.next;
        //     }
        // }else{
        //     console.log('the elemenet '+data+' is not exist');
        // }
    };

    //isEmpty()
    Linkedlist.prototype.isEmpty = function(){
        console.log(this.size ==0);
        return;
    };

    //size()
    Linkedlist.prototype.length = function(){
        console.log('the size of linkedlist is '+this.size);
        return;
    };

    // toString
    Linkedlist.prototype.toString = function(){
        if (this.size == 0) {
            console.log('No Elemenet');
            return;
        }
        let current = this.head;
        let liststring = "";
        while(current){
            liststring += current.data+" ";
            current = current.next;
        }
        console.log(liststring);
        return;
    };
}

var linkedlist = new Linkedlist;
linkedlist.append(1);
linkedlist.append(2);
linkedlist.append(30);
linkedlist.append(4);
linkedlist.append(5);
linkedlist.append(6);
linkedlist.toString();
linkedlist.insert('a', 2);
linkedlist.toString();
linkedlist.update('b', 2);
linkedlist.toString();
linkedlist.get(2);
linkedlist.isEmpty();
linkedlist.length();
linkedlist.toString();
linkedlist.indexOf('4');
linkedlist.removeAt(0);
linkedlist.toString();
linkedlist.length();
linkedlist.removeAt(5);
linkedlist.toString();
linkedlist.remove(2);
linkedlist.toString();
1 2 30 4 5 6 
1 2 a 30 4 5 6 
1 2 b 30 4 5 6 
at Position of 2 is: b
false
the size of linkedlist is 7
1 2 b 30 4 5 6 
the elemenet 4 is at position of 4
2 b 30 4 5 6 
the size of linkedlist is 6
2 b 30 4 5 
the elemenet 2 is at position of 0
b 30 4 5 

Python

class LinkNode:
    def __init__(self, data=None, next=None):
        self.data = data
        self.next = next


class Demo:
    def __init__(this):
        this.LinkedList = LinkNode(0)
        this.point = this.LinkedList

    def insert(this, x):
        this.point.next = LinkNode(x)
        this.point = this.point.next

    def create(this, numbers):
        for i in numbers:
            this.point.next = LinkNode(i)
            this.point = this.point.next

    def delete(this, value):
        # while(this.LinkedList.data != value):
        #     this.LinkedList = this.LinkedList.next
        # this.LinkedList = this.LinkedList.next
        index = this.LinkedList
        while(index.data != value):
            prev = index
            index = index.next
        prev.next = index.next


if __name__ == "__main__":
    demo = Demo()
    demo.create([1, 2, 3, 4, 5, 6, 7])
    demo.insert(10)
    demo.delete(5)
    while (demo.LinkedList):
        print(demo.LinkedList.data)
        demo.LinkedList = demo.LinkedList.next

0
1
2
3
4
6
7
10

DoubleVerketteList

C/C++

#include <stdio.h>
#include <stdlib.h>
#define N 10

typedef struct node{
  struct node* pronode;
  int data;
  struct node *nextnode;
}node;

node *initnode( node *p){
  p = (node *)malloc(sizeof(node));
  p->pronode = NULL;
  p->nextnode = NULL;
  p->data = 1;
  node *temp = p;
  for (int i = 1; i < N; ++i) {
    node *a =(node *)malloc(sizeof(node));
    a->nextnode = NULL;
    a->pronode = NULL;
    a->data = i+1;
    temp->nextnode = a;
    a->pronode = temp;
    temp = temp->nextnode;
  }
  return p;
}

void display(node *p){
  node *temp = p;
  while (temp) {
    while (temp->nextnode) {
      printf("%d ",temp->data );
      temp = temp->nextnode;
    }
    printf(", and  the last is %d\n",temp->data );
    temp = temp->nextnode;
  }
}

void insert(node *p, int x, int pos){
  node *a =(node *)malloc(sizeof(node));
  a->data = x;
  a->nextnode = NULL;
  a->pronode = NULL;
  if (x == 1) {
    a->nextnode = p;
    p->pronode = a;
    p = a;
  }else {
    node *temp = p;
    for (int i = 1; i < pos-1; i++) {
      temp = temp->nextnode;
    }
    if (temp->nextnode == NULL) {
      temp->nextnode = a;
      a->pronode = temp;
    }else {
      a->nextnode = temp->nextnode;
      temp->nextnode = a;
      a->pronode = temp;
      a->nextnode->pronode = a;   
      /* temp->nextnode->pronode = a; */  // this line do the same as last one, why???
      printf("%s\n", "nihao");
    }
  }
}

node *delete(node *p, int x){
  node *temp = p;  
  if (p->data == x) {
    p = p->nextnode;
    free(temp);
    return p;
  }

  while (temp->nextnode->nextnode != NULL && temp->nextnode->data != x) {
    temp = temp->nextnode;
  }
  if (temp->nextnode->nextnode == NULL) { // check if it is the last element
    if (temp->nextnode->data == x) {      // check if it is what we want 
      temp->nextnode = NULL;
      free(temp->nextnode);
      return p;
    }else {
      printf("there is no element of %d\n", x);
      return p;
    }
  }else {
    temp->nextnode = temp->nextnode->nextnode;
    temp->nextnode->pronode= temp;
    return p;
  }
}

int main(int argc, char *argv[])
{
  node *head = NULL;
  head = initnode(head);
  display(head);
  insert(head, 100, 6);
  display(head);
  delete(head, 100);
  display(head);
  /* 1, if only one elemenet in list */
  /* 2, execute : temp->nextnode->nextnode != NULL && temp->nextnode->data != x */
  /* 3, if while stop, check if temp->nextnode is the last element */
  /* 4, if temp->nextnode is what we want */
  node * p = delete(head, 2);
  display(p);
  return 0;
}
1 2 3 4 5 6 7 8 9 , and  the last is 10
nihao
1 2 3 4 5 100 6 7 8 9 , and  the last is 10
1 2 3 4 5 6 7 8 9 , and  the last is 10
1 3 4 5 6 7 8 9 , and  the last is 10

JS


append(elemenet) append element at the end of list insert(elemenet, position) insert elemenet at position of position update(position, elemenet) update the data to elemenet at position get(position) get the elemenet at position indexOf(elemenet) return the position of elemenet removeAt(position) remove the elemenet at position remove(elemenet) remove the elemenet no matater where it is isEmpty()
size() length of list toString()
forwardtoString()
backwardtoString()


function Doublelinkedlist(){
    //initialization
    this.head = null;
    this.tail = null;
    this.size = 0;
    function Node(data){
        this.data = data;
        this.perv = null;
        this.next = null;
    }
    // append(data)
    Doublelinkedlist.prototype.append = function(data){
        var node = new Node(data);
        if (this.size == 0) {
            this.head = node;
            this.tail = node;
        }else{
            var current = this.head;
            while(current.next){
                current = current.next;
            }
            current.next = node;
            node.perv = current;
            this.tail = node;
        }
        this.size += 1;
    };
    // insert(elemenet, position)
    Doublelinkedlist.prototype.insert = function(data, position){
        if (position < 0 || position >= this.size) {
            console.log('the position to insert is invalid');
            return;
        };
        var node = new Node(data);
        if (position == 0) {
            this.head.perv = node;
            node.next = this.head;
            this.head = node;
            this.size += 1;
            return;
        }else if(position == this.size-1){
            this.tail.next = node;
            node.perv = this.tail;
            this.tail = node;
            this.size += 1;
            return;
        }else{
            let tmp = 0;
            var current = this.head;
            while(tmp++ < position){
                current = current.next;
            }
            current.perv.next = node;
            node.perv = current.perv;
            node.next = current;
            current.perv = node;
            this.size += 1;
            return;
        }
    };
    // update(elemenet, position)
    Doublelinkedlist.prototype.update = function(data, position){
        if (position < 0 || position >= this.size) {
            console.log('the position to insert is invalid');
            return;
        };
        let tmp = 0;
        let current = this.head;
        while(tmp++ < position){
            current = current.next;
        }
        current.data = data;
    };
    // get(position)
    Doublelinkedlist.prototype.get = function(position){
        if (position < 0 || position >= this.size) {
            console.log('the position to insert is invalid');
            return;
        };
        var current = this.head;
        let tmp = 0;
        while(tmp++ < position){
            current = current.next;
        }
        return current.data;
    };


    // indexOf(elemenet)
    Doublelinkedlist.prototype.indexOf = function(data){
        var tmp = 0;
        var current = this.head;
        while(current){
            if (current.data == data) {
                return tmp;       
            }
            current = current.next;
            tmp += 1;
        };
        if (!current) {
            console.log('elemenet '+data+' is not in list');
            return -1;
        }
    };

    // removeAt(position)
    Doublelinkedlist.prototype.removeAt = function(position){
        if (position < 0 || position >= this.size) {
            console.log('the position to insert is invalid');
            return;
        };
        if (position == 0) {
            this.head.next.perv = null;
            this.head = this.head.next;
            this.size -= 1;
            return;
        }else if(position == this.size-1){
            this.tail.perv.next = null;
            this.tail = this.tail.perv;
            this.size -= 1;
            return;
        }else{
            var tmp = 0;
            var current = this.head;
            while(tmp++ < position){
                current = current.next;
            }
            current.perv.next = current.next;
            current.next.perv = current.perv;
            this.size -= 1;
            return;
        }
    };


    // remove(elemenet)
    Doublelinkedlist.prototype.remove = function(data){
        var index = this.indexOf(data);
        this.removeAt(index);
    };

    // isEmpty()
    Doublelinkedlist.prototype.isEmpty = function(){
        return this.size == 0;
    };
    //  length()
    Doublelinkedlist.prototype.length = function(){
        return this.size;
    };
    //forwardtoString()
    Doublelinkedlist.prototype.forwardtoString = function(){
        let current = this.head;
        let string = '';
        while(current){
            string += current.data + '  ';
            current = current.next;
        }
        console.log(string);
    };
    //backwardtoString()
    Doublelinkedlist.prototype.backwardtoString = function(){
        let current = this.tail;
        let string = '';
        while(current){
            string += current.data + '  ';
            current = current.perv;
        }
        console.log(string);
    };
    //toString
    Doublelinkedlist.prototype.toString = function(){
        this.forwardtoString();
    };
}

var doublelinkedlist = new Doublelinkedlist();
doublelinkedlist.append(1);
doublelinkedlist.append(2);
doublelinkedlist.append(3);
doublelinkedlist.append(4);
doublelinkedlist.append(5);
doublelinkedlist.append(6);
doublelinkedlist.forwardtoString();
doublelinkedlist.backwardtoString();
doublelinkedlist.toString();
console.log(doublelinkedlist.isEmpty());
console.log(doublelinkedlist.length());
doublelinkedlist.insert('a', 0);
doublelinkedlist.insert('b', doublelinkedlist.length()-1);
doublelinkedlist.insert('c', 1);
doublelinkedlist.toString();
doublelinkedlist.update('A', 0);
doublelinkedlist.update('B', doublelinkedlist.length()-1);
doublelinkedlist.update('C', 1);
doublelinkedlist.toString();
console.log(doublelinkedlist.get(0));
console.log(doublelinkedlist.indexOf('B'));
doublelinkedlist.removeAt(0)
doublelinkedlist.removeAt(doublelinkedlist.length()-1);
doublelinkedlist.toString();
doublelinkedlist.removeAt(1)
doublelinkedlist.toString();
doublelinkedlist.remove('C')
doublelinkedlist.remove(6)
doublelinkedlist.remove(4)
doublelinkedlist.toString();
1  2  3  4  5  6  
6  5  4  3  2  1  
1  2  3  4  5  6  
false
6
a  c  1  2  3  4  5  6  b  
A  C  1  2  3  4  5  6  B  
A
8
C  1  2  3  4  5  6  
C  2  3  4  5  6  
2  3  5  

SingelKetteLinkeWithHead

C/C++

/* 带头节点 */
/* 建(创建C1) */
/* 查( 全查R1,  靠值查R2,   靠位查R3 ) */
/* 改 (         靠值改U1,  靠位改U2) */
/* 增(头插A1, 尾插A2,中值插A3, 中位插A4) */
/* 删(头删D1, 尾删D2,中值删D3, 中位删D4) */

#include <stdio.h>
#include <stdlib.h>

typedef struct Link{
  int elem;
  struct Link *next;
}link;

link *initLinkC1(int j){
  link *p = (link *)malloc(sizeof(link));
  link *temp = p;
  int i;
  for (i=1; i <= j; i++) {
    link *a = (link *)malloc(sizeof(link));
    a->elem = i;
    a->next = NULL;
    temp->next = a;
    temp = temp->next;
  }
  return p;
}

void displayR1(link *p){
  link *temp = p;
  while(temp->next){
    printf("%d ",temp->next->elem);
    temp = temp->next;
  }
  printf("\n");
}

int displayR2(link *p, int k){
  link *temp = p;
  while (temp->next) {
    if (temp->next->elem == k) {
      return temp->next->elem;
    }
    temp = temp->next;
  }
  if (temp->next == NULL) {
    printf("the %d is not found \n", k);
  }
  return k;
}

int displayR3(link *p, int k){
  link *temp = p;
  int i = 0;
  while (i < k && temp->next) {
    temp = temp->next;
    i++;
  }
  if (i != k) {
    printf("the %d postion element is not found\n",k );
    return -1;
  }
  return temp->elem;
}

void changeelementU1(link *p, int i, int k){
  link *temp = p;
  while (temp->next != NULL){
    if (temp->elem == i){
      break;
    }
    temp = temp->next;
  }

  if (temp->next == NULL) {   // if temp is the last element,
    if (temp->elem != i) {    // if the last element is not what we want
      printf("there is no element which contains %d\n",i );
    }else {
      temp->elem = k;        // if the last one is what we want
    }
  }else {
    temp->elem = k;          // if temp is not the last one
  }
}

void changeelementU2(link *p, int i, int k){
  link *temp = p;
  int m = 0;
  while (m < i && temp->next != NULL){
    temp = temp->next;
    m++;
  }
  if (m != i) {             // if the length of list is shorter than given i
    printf("the %d postion element is not found\n",i );    
  }else {
    temp->elem = k;
  }
}

void addelementA1(link *p, int k){
  link *a = (link *)malloc(sizeof(link));
  a->elem = k;
  a->next = p->next;
  p->next = a;
}

void addelementA2(link *p, int k){
  link *temp = p;
  while (temp->next->next != NULL) {
    temp = temp->next;
  }
  link *a = (link *)malloc(sizeof(link));
  a->elem = k;
  a->next = NULL;
  temp->next->next = a;
}

void addelementA3(link *p, int i, int k){
  link *temp = p;
  while (temp->next != NULL) {
    if (temp->next->elem == i) {
      break;
    }
    temp = temp->next;
  }
  if (temp->next == NULL) {    // if temp is the last element
    if (temp->elem != i) {     // if the last element is not what we want :temp->elem != k
      printf("there is no element which contains %d\n",k );
    }else {                     // if the last element is what we want: temp->elem == k
      link *a = (link *)malloc(sizeof(link));
      a->elem = k;
      a->next = NULL;
      temp->next = a;
    }
  }else {                       // if temp->next->elem == k
    link *a = (link *)malloc(sizeof(link));
    a->elem = k;
    a->next = NULL;
    /* add the element behind i */
    a->next = temp->next->next;
    temp->next->next = a;
    /* add the element front of i */
    /* a->next = temp->next; */
    /* temp->next = a; */
  }
}

void addelementA4(link *p, int i, int k){
  link *temp = p;
  int m = 0;
  while (m < i && temp->next != NULL) {
    temp = temp->next;
    m++;
  }
  if (m != i) {                    // the length of list is shorter than i
      printf("the %d postion element is not found\n",i);
  }else if(!temp->next) {            // if temp is the last element of list      
      link *a = (link *)malloc(sizeof(link));
      a->elem = k;
      a->next = NULL;
      temp->next = a;
  }else {                           // if temp is not the element of list
    link *a = (link *)malloc(sizeof(link));
    a->elem = k;
    a->next = NULL;
    a->next = temp->next->next;
    temp->next->next = a;
    /* add the element front of i */
    /* a->next = temp->next; */
    /* temp->next = a; */
  }
}

void deleteelementD1(link *p){
  p->next = p->next->next;
}

void deleteelementD2(link *p){
  link *temp = p;
  while(temp->next->next){
    temp = temp->next;
  }
  temp->next = NULL;
  free(temp->next);
}

void deleteelementD3(link *p, int k){
  link *temp = p;
  while (temp->next->next != NULL){
    if (temp->next->elem == k){
      break;
    }
    temp = temp->next;
  }
  if (temp->next->next == NULL) {      // if temp->next is the last element
    if(temp->next->elem != k) {         // temp->next is the last, but it's not what we want
      printf("there is no element which contains %d\n",k );
    }else{                               // temp->next is the last, but is what we want
      temp->next = NULL;
      free(temp->next);
    }
  }else{                               // temp->next is not the last, so it must be what we look for
    temp->next = temp->next->next;
  }
}

void deleteelementD4(link *p, int k){
  link *temp = p;
  if (k == 1) {
    if (temp->next->next == NULL) {   // only one element auf dem List
      temp->next = NULL;
      free(temp->next);
      return;
    }else {
      temp->next = temp->next->next;
      return;
    }
  }
  // if k >=  2 and there are more than or equal 2 elements in list
  int m = 0;             
  while (m < k-1 && temp->next->next != NULL){
    temp = temp->next;
    m++;
  }
  if (m != k-1) {                              // list is shorter than k
    printf("the %d postion element is not found\n",k);
  }else if(temp->next->next == NULL){            // if temp->next->next is the last element
    temp->next = NULL;
    free(temp->next);
  }else{                                        // if temp->next->next is not the last element
    temp->next = temp->next->next;
  }
}

link *reserve(link* p){
  link * begin = NULL;
  link * mid = p->next;
  link * end = p->next->next;
  while (end) {
    mid->next = begin;
    begin = mid;
    mid = end;
    end = end->next;
  }
  mid->next = begin;
  link *m =(link *)malloc(sizeof(link));
  m->next = mid;
  return m;
}

int main(int argc, char *argv[])
{
  /* 建(创建C1) */
  link *p = initLinkC1(9);
  printf("generate the list from 1 to 9 \n");
  /* 查( 全查R1,  靠值查R2,   靠位查R3 ) */  
  displayR1(p);
  int r2 = 3;
  printf("check if we can find %d in the list, and  to be %d\n", r2, displayR2(p, r2));
  int r3 = 10;
  printf("check if we can find %d postion in the list, and to be %d\n", r3, displayR3(p, r3));
  /* 改 (         靠值改U1,  靠位改U2) */
  printf("change the element 9 to 10 \n");
  changeelementU1(p, 9, 10);
  displayR1(p);
  printf("change the postion 9 to 10 \n");
  changeelementU2(p, 9, 11);
  displayR1(p);
  /* 增(头插A1, 尾插A2,中值插A3, 中位插A4) */
  printf("add 0 to the begin of list \n");
  addelementA1(p, 0);
  displayR1(p);
  printf("add 20 to the end of list \n");
  addelementA2(p, 20);
  displayR1(p);
  printf("add 18 to the list behind element 2 \n");
  addelementA3(p, 2, 15);
  displayR1(p);
  printf("add 18 to the list behind  postion 2 \n");
  addelementA4(p, 1, 18);
  displayR1(p);
  /* 删(头删D1, 尾删D2,中值删D3, 中位删D4) */
  printf("delete the frist lement \n");
  deleteelementD1(p);
  displayR1(p); 
  printf("delete the the last element \n");
  deleteelementD2(p);
  displayR1(p);
  printf("delete the element 1 \n");
  deleteelementD3(p, 1);
  displayR1(p);
  printf("delete the postion 2 \n");
  deleteelementD4(p, 2);
  displayR1(p);
  /* reverse倒叙  */
  /* 1 去掉头节点 */
  /*   2 从第一个元素开始反转,并连接 */
  /*   3 到end = null 停止 */
  /*   4 连接最后一个元素 */
  /*   5 开辟新的头节点 */
  /*   6 连接头节点,并返回 */
  printf("reserve the list\n");
  link *m = reserve(p);
  displayR1(m);
  return 0;
}


generate the list from 1 to 9 
1 2 3 4 5 6 7 8 9 
check if we can find 3 in the list, and  to be 3
the 10 postion element is not found
check if we can find 10 postion in the list, and to be -1
change the element 9 to 10 
1 2 3 4 5 6 7 8 10 
change the postion 9 to 10 
1 2 3 4 5 6 7 8 11 
add 0 to the begin of list 
0 1 2 3 4 5 6 7 8 11 
add 20 to the end of list 
0 1 2 3 4 5 6 7 8 11 20 
add 18 to the list behind element 2 
0 1 2 15 3 4 5 6 7 8 11 20 
add 18 to the list behind  postion 2 
0 1 18 2 15 3 4 5 6 7 8 11 20 
delete the frist lement 
1 18 2 15 3 4 5 6 7 8 11 20 
delete the the last element 
1 18 2 15 3 4 5 6 7 8 11 
delete the element 1 
18 2 15 3 4 5 6 7 8 11 
delete the postion 2 
18 15 3 4 5 6 7 8 11 
reserve the list
11 8 7 6 5 4 3 15 18

DoubleRecycleVerketteList

C/C++

#include <stdio.h>
#include <stdlib.h>
#define N 10
typedef struct node {
  struct node * Nnode;
  struct node * Pnode;
  int data;
}node;

node *initDoubleRecycleVerketteList(int x){
  node * head = (node *)malloc(sizeof(node));
  head->data = 1;
  head->Nnode = NULL;
  head->Pnode = NULL;
  node * temp = head;
  for (int i = 2; i <=x; i++){
    node * a = (node *)malloc(sizeof(node));
    a->data = i;
    a->Nnode = NULL;
    a->Pnode = NULL;

    temp->Nnode = a;
    a->Pnode = temp;
    temp = temp->Nnode;
  }
  temp->Nnode = head;
  head->Pnode = temp;
  return head;
}

void display(node *p){
  node *temp = p;
  if (p != NULL) {
    do{
      printf("%d ", temp->data);
      temp = temp->Nnode;
    } while (temp != p);
  }else {
    printf("the list is empty\n");
  }
}  

int main(int argc, char *argv[])
{
  node * head = initDoubleRecycleVerketteList(N);
  display(head);
  return 0;
}

1 2 3 4 5 6 7 8 9 10

Priority Queues

description

Priority Queues is a set of instances, which
are sorted according to their keys
This can be implemented by binary heap
Heap sort all key with a Max-heap A

show-Max(A)

return A[0]

Extract-Max(A)

max = A[0]
A[0] <- A[A.heap_size]
A.heap_size--
Max-heap(A,A.heap_size, 0)
return max

Heap-increase-key(A, i, k)

increase the elemenet with i priority to k priority

A[i] <- k
while i > 1 and A[i] > A[parent(i)]:
    exchange (A[i], A[parent(i)])
    exchange (i, parent(i))

Heap-insert(A, k)

A.heap_size++
A[A.heap_size] = -\inf
Heap-include-key(A, A.heap_size, k)

StaticKetteList

C/C++

#include <stdio.h>
#define maxSize 6
typedef struct {
    int data;
    int cur;
}component;
//将结构体数组中所有分量链接到备用链表中
void reserveArr(component *array);
//初始化静态链表
int initArr(component *array);
//输出函数
void displayArr(component * array,int body);
//从备用链表上摘下空闲节点的函数
int mallocArr(component * array);
int main() {
    component array[maxSize];
    int body=initArr(array);
    printf("静态链表为:\n");
    displayArr(array, body);
    return 0;
}
//创建备用链表
void reserveArr(component *array){
    for (int i=0; i<maxSize; i++) {
        array[i].cur=i+1;//将每个数组分量链接到一起
        array[i].data=-1;
    }
    array[maxSize-1].cur=0;//链表最后一个结点的游标值为0
}
//提取分配空间
int mallocArr(component * array){
    //若备用链表非空,则返回分配的结点下标,否则返回 0(当分配最后一个结点时,该结点的游标值为 0)
    int i=array[0].cur;
    if (array[0].cur) {
        array[0].cur=array[i].cur;
    }
    return i;
}
//初始化静态链表
int initArr(component *array){
    reserveArr(array);
    int body=mallocArr(array);
    //声明一个变量,把它当指针使,指向链表的最后的一个结点,因为链表为空,所以和头结点重合
    int tempBody=body;
    for (int i=1; i<4; i++) {
        int j=mallocArr(array);//从备用链表中拿出空闲的分量
        array[tempBody].cur=j;//将申请的空闲分量链接在链表的最后一个结点后面
        array[j].data=i;//给新申请的分量的数据域初始化
        tempBody=j;//将指向链表最后一个结点的指针后移
    }
    array[tempBody].cur=0;//新的链表最后一个结点的指针设置为0
    return body;
}

void displayArr(component * array,int body){
  int tempBody=body;//tempBody准备做遍历使用
    while (array[tempBody].cur) {
        printf("%d,%d ",array[tempBody].data,array[tempBody].cur);
        tempBody=array[tempBody].cur;
    }
    printf("%d,%d\n",array[tempBody].data,array[tempBody].cur);
}

静态链表为:
-1,2 1,3 2,4 3,0

Lookup Table

C/C++

#include <stdio.h>
#include <stdlib.h>
#define  KeyType int
typedef struct{
  KeyType key;
}ElemType;

typedef struct{
  ElemType *elem;
  int length;
}SSTable;

void create(SSTable ** table, int *context , int length){
  (*table)=(SSTable*)malloc(sizeof(SSTable));
  (*table)->length = length;
  (*table)->elem = (ElemType*)malloc((length+1)*sizeof(ElemType));
  for (int i =1; i <= length; i++) {
    (*table)->elem[i].key = *(context+i-1);
  }
}

int search(SSTable *table, int lookup){
  table->elem[0].key = lookup;
  int i = table->length;
  while (table->elem[i].key != table->elem[0].key) {
    i--;
  }
  return i;
}

int main(int argc, char *argv[])
{
  int context[] = {1, 3, 7, 23, 56, 89, 345};
  int length =  sizeof(context)/sizeof(int);
  SSTable *table;
  create(&table, context, length);
  int lookup = 3;
  int localation = search(table, lookup);
  if (localation) {
    printf("In\n");
  }else {
    printf("NOT In\n");
  }
  return 0;
}

In

Set

JS

function Dictionay() {
    // initialization
    this.items = {};
    Dictionay.prototype.set = function (key, value) {
        this.items[key] = value;
    };

    //has(key)
    Dictionay.prototype.has = function (key) {
        return this.items.hasOwnProperty(key);
    };

    //remove(key)
    Dictionay.prototype.remove = function (key) {

        if (!this.has(key)) return false;


        delete this.items[key];
        return true;
    };
    //get(key)
    Dictionay.prototype.get = function (key) {
        return this.has(key) ? this.items[key] : undefined;
    };

    //keys()
    Dictionay.prototype.keys = function () {
        return Object.keys(this.items);
    };

    //values()
    Dictionay.prototype.values = function () {
        return Object.values(this.items);
    };

    //size()
    Dictionay.prototype.size = function () {
        return this.keys().length;
    };

    //clear()
    Dictionay.prototype.clear = function () {
        this.items = {};
    };
}


var dict = new Dictionay();

dict.set("age", 18);
dict.set("name", "Coderwhy");
dict.set("height", 1.88);
dict.set("address", "广州市");

console.log(dict.keys()); // age,name,height,address
console.log(dict.values()); // 18,Coderwhy,1.88,广州市
console.log(dict.size()); // 4
console.log(dict.get("name")); // Coderwhy
dict.remove("height");
console.log(dict.keys());// age,name,address
dict.clear();

[ 'age', 'name', 'height', 'address' ]
[ 18, 'Coderwhy', 1.88, '广州市' ]
4
Coderwhy
[ 'age', 'name', 'address' ]

HashTable

JS

simple example

function HashTable(){
    //initialization
    this.limit = 7;
    this.storage = [];
    this.conut = 0;

    //hash()
    HashTable.prototype.hash = function(key){
        var hashCode = 0;
        for (var i = 0; i < key.length; i++) {
            hashCode =37*hashCode + key.charCodeAt(i);
        }
        hashCode = hashCode % this.limit;
        return hashCode;
    };
    //put(key, value)
    HashTable.prototype.put = function(key, value){
        var index = this.hash(key);
        var bucket = this.storage[index];
        if (bucket == null) {
            bucket = [];
            this.storage[index] = bucket;
        }
        var override = false;
        for (var i = 0; i < bucket.length; i++) {
            var tuple = bucket[i];
            if (tuple[0] == key) {
                tuple[1] = value;
                override = true;
            }
        }
        if (!override) {
            bucket.push([key, value]);
            this.conut += 1;
        }
    };

    //get(key)
    HashTable.prototype.get = function(key){
        var index = this.hash(key);
        var bucket = this.storage[index];
        if (bucket == null) {
            return null;
        }
        for (var i = 0; i < bucket.length; i++) {
            var tuple = bucket[i];
            if (tuple[0] == key) {
                return tuple[1];
            };
        };
        return null;
    };
    //remove(key)
    HashTable.prototype.remove = function(key){
        var index = this.hash(key);
        var bucket = this.storage[index];
        if (bucket == null) {
            return null;
        }
        for (var i = 0; i < bucket.length; i++) {
            var tuple = bucket[i];
            if (tuple[0]== key){
                bucket.splice(i, 1);
                this.conut--;
                return tuple[1];
            }
        };
        return null;
    };
    //isEmpty()
    HashTable.prototype.isEmpty = function(){
        return this.conut == 0;
    };
    //size()
    HashTable.prototype.size = function(){
        return this.conut;
    };
}

var ht = new HashTable();
ht.put("abc", 1);
ht.put("bcd", 2);
ht.put("cde", 3);
ht.put("def", 4);
ht.put("efg", 5);
ht.put("fgh", 6);

console.log(ht.get("aaa"));
Console.log(ht.get("abc"));
console.log(ht.remove("bcd"));
console.log(ht.get("def"));


null
1
2
4

void swap(int *a, int *b){ int tmp = *a; ,*a = *b; ,*b = tmp; } void heapify(int A[], int N, int i){ int leftchild = i*2+1; int rightchild = i*2+2; int maxindex = i; if (leftchild < N && A[leftchild] > A[maxindex]) { maxindex = leftchild; } if (rightchild < N && A[rightchild] > A[maxindex]) { maxindex = rightchild; } if (maxindex != i) { swap(A[maxindex], A[i]); heapify(A, N, maxindex); } }

void build~heap~(int A[], int N){ int last~parent~ = (N-1-1)/2; int i; for (i = last~parent~; i >= 0; i--) { heapify(A, N, i); } }

int main(int argc, char *argv[]) { int A[] = {2, 1, 3, 4, 5, 3, 6, 7, 8, 4, 9, 45, 9,34, 23,345, 546,20, 23465, 90, 19}; int N = sizeof(A)/sizeof(int); build~heap~(A, N); for (int i = N-1; i >= 0; i--) { swap(A[i], A[0]); heapify(A, i, 0); }

for (int j = 0; j < N; ++j) { printf("%d ",A[j]); } return 0; }

vollstangdig example

function HashTable() {
    // 定义属性
    this.storage = []
    this.count = 0
    this.limit = 8

    // 定义相关方法
    // 判断是否是质数
    HashTable.prototype.isPrime = function (num) {
        var temp = parseInt(Math.sqrt(num))
        // 2.循环判断
        for (var i = 2; i <= temp; i++) {
            if (num % i == 0) {
                return false
            }
        }
        return true
    }

    // 获取质数
    HashTable.prototype.getPrime = function (num) {
        while (!isPrime(num)) {
            num++
        }
        return num
    }

    // 哈希函数
    HashTable.prototype.hashFunc = function(str, max) {
        // 1.初始化hashCode的值
        var hashCode = 0

        // 2.霍纳算法, 来计算hashCode的数值
        for (var i = 0; i < str.length; i++) {
            hashCode = 37 * hashCode + str.charCodeAt(i)
        }

        // 3.取模运算
        hashCode = hashCode % max
        return hashCode
    }

    // 插入数据方法
    HashTable.prototype.put = function (key, value) {
        // 1.获取key对应的index
        var index = this.hashFunc(key, this.limit)

        // 2.取出数组(也可以使用链表)
        // 数组中放置数据的方式: [[ [k,v], [k,v], [k,v] ] , [ [k,v], [k,v] ]  [ [k,v] ] ]
        var bucket = this.storage[index]

        // 3.判断这个数组是否存在
        if (bucket === undefined) {
            // 3.1创建桶
            bucket = []
            this.storage[index] = bucket
        }

        // 4.判断是新增还是修改原来的值.
        var override = false
        for (var i = 0; i < bucket.length; i++) {
            var tuple = bucket[i]
            if (tuple[0] === key) {
                tuple[1] = value
                override = true
            }
        }

        // 5.如果是新增, 前一步没有覆盖
        if (!override) {
            bucket.push([key, value])
            this.count++

            if (this.count > this.limit * 0.75) {
                var primeNum = this.getPrime(this.limit * 2)
                this.resize(primeNum)
            }
        }
    }

    // 获取存放的数据
    HashTable.prototype.get = function (key) {
        // 1.获取key对应的index
        var index = this.hashFunc(key, this.limit)

        // 2.获取对应的bucket
        var bucket = this.storage[index]

        // 3.如果bucket为null, 那么说明这个位置没有数据
        if (bucket == null) {
            return null
        }

        // 4.有bucket, 判断是否有对应的key
        for (var i = 0; i < bucket.length; i++) {
            var tuple = bucket[i]
            if (tuple[0] === key) {
                return tuple[1]
            }
        }

        // 5.没有找到, return null
        return null
    }

    // 删除数据
    HashTable.prototype.remove = function (key) {
        // 1.获取key对应的index
        var index = this.hashFunc(key, this.limit)

        // 2.获取对应的bucket
        var bucket = this.storage[index]

        // 3.判断同是否为null, 为null则说明没有对应的数据
        if (bucket == null) {
            return null
        }

        // 4.遍历bucket, 寻找对应的数据
        for (var i = 0; i < bucket.length; i++) {
            var tuple = bucket[i]
            if (tuple[0] === key) {
                bucket.splice(i, 1)
                this.count--

                // 缩小数组的容量
                if (this.limit > 7 && this.count < this.limit * 0.25) {
                    var primeNum = this.getPrime(Math.floor(this.limit / 2))
                    this.resize(primeNum)
                }
            }
            return tuple[1]
        }

        // 5.来到该位置, 说明没有对应的数据, 那么返回null
        return null
    }

    // isEmpty方法
    HashTable.prototype.isEmpty = function () {
        return this.count == 0
    }

    // size方法
    HashTable.prototype.size = function () {
        return this.count
    }

    // 哈希表扩容
    HashTable.prototype.resize = function (newLimit) {
        // 1.保存旧的数组内容
        var oldStorage = this.storage

        // 2.重置属性
        this.limit = newLimit
        this.count = 0
        this.storage = []

        // 3.遍历旧数组中的所有数据项, 并且重新插入到哈希表中
        oldStorage.forEach(function (bucket) {
            // 1.bucket为null, 说明这里面没有数据
            if (bucket == null) {
                return
            }

            // 2.bucket中有数据, 那么将里面的数据重新哈希化插入
            for (var i = 0; i < bucket.length; i++) {
                var tuple = bucket[i]
                this.put(tuple[0], tuple[1])
            }
        }).bind(this)
    }
}


Binary tree

By delete:


without child just delete with one child just overwirte itself with two child with precursor or Successor and recursive if necessary


RedBlack tree

5 Rules

  • alle node red or black
  • root black
  • leaf black null
  • red can't together
  • all path has the same number of black

2 whirl

  • left whirl, Counterclockwise
  • right whirl, clockwise

just whirl, if there is a node or a branch between the two whirled node, after the whirling, it's still in the between!!!

5 casese to add new red node


1 no root add root 2 black father just add new node 3 red father, red uncle black father, black uncle, red grandfather 4 red father, black uncle, left child black father, black uncle, red grandfather, right whirl 5 red father, black uncle, right child left whirl, to step 4


3,4,5 will be repeated if necessary!

Cartesian tree

this tree has two property,
1, it's a heap, which mean, the parents are all smaller than their childen
2, we can get the original array with the IN-order scan of the tree

How to build cartesian tree
for inserting a new node, we compare it to the root and the rightest edge,
if it is smaller than the root, trun the all(include the root) to be new node's left child
if it is bigger, go down to the next node, if go to the leaf, add it just as right child
if it is bigger, go down to the next node, if it is smaller than one node,
                                           trun all to be the left child, and new node as right chilc

this can be done in time compexity

Binary Heap

Binary Heap example deviced by heap sort

let swap = function (left:number, right:number){
  return [right, left]
  }

let heapfly =  function(list:number[], length:number, index:number){
      var leftchild = index*2+1
      var rightchild = index*2+2
      var maxindex = index
      if (leftchild < length && list[leftchild] >list[maxindex]) {
          [leftchild, maxindex] = swap(leftchild, maxindex)
      }

    if (rightchild < length && list[rightchild]>list[maxindex]) {
        [rightchild, maxindex] = swap(rightchild, maxindex)
      }
      if (maxindex != index) {
          [list[maxindex], list[index]] = swap(list[maxindex], list[index])
          heapfly(list, length, maxindex)
      }
  }
 let build_heap = function (list:number[], lenght:number){
      var lastperent = Math.floor((length-1-1) / 2);
      for (var i = lastperent; i >= 0; i--) {
          heapfly(list, length, i);
      }
  }
  var list: number[] = [2, 1, 3, 4, 5, 3, 5, 7, 8, 45,  9, 25, 34, 23, 345, 546, 20, 23465, 90, 19];
  console.log(list)
  var length: number = list.length;
  build_heap(list, length)

  for (var i = length-1; i >= 0; i--) {
      [list[i], list[0]]= swap(list[i], list[0])
      heapfly(list, i, 0)
  }
  console.log(list)

[
    2,  1,     3,  4,   5,
    3,  5,     7,  8,  45,
    9, 25,    34, 23, 345,
  546, 20, 23465, 90,  19
]
[
   1,  2,   3,   3,     4,
   5,  5,   7,   8,     9,
  19, 20,  23,  25,    34,
  45, 90, 345, 546, 23465
]

Binomial-tree

Definition: if k > 0, .

digraph diagramm {
A0;
B0 -> B1;
C0 -> C1;
C0 -> C2;
C2 -> C3;
D0 -> D1; 
D0 -> D2;
D0 -> D3;
D2 -> D4;
D3 -> D5;
D3 -> D6;
D6 -> D7;

}   

Binomial Heap

Binomial Heap is a forest of binomial Tree
1. all binomial tree are min(max)imum heap property
2. with different order Binomial Tree consist Binomial Heap, non duplicated order binomial tree
digraph diagramm {
A0;
A0 -> B0;
B0 -> B1;

B0 -> C0;
C0 -> C1;
C0 -> C2;
C2 -> C3;

C0 -> D0;
D0 -> D1; 
D0 -> D2;
D0 -> D3;
D2 -> D4;
D3 -> D5;
D3 -> D6;
D6 -> D7;
}   

Each order has only one Binomial Tree, conlidataion is required at each min-extract, merge

Fibonacci Heap

lazy Binomial Heap

For merge Operation:
Just concatenate the two binomial Heap, without the consolidation step

For Min-extra:
after extracte the minmum we merge  the root list.
the conlidataion will not be executed after merge, until now
clean the masse

key-decrease O(1)

key-decrease is also lazy, just cut it off, and add to rootlist

amortised Min-extra to

amortised operation reduce Min-extra to

damaged Fibonacci Heap

For all perents, if one child is loss, will be marked as red, if the second also loss, the perent will be cut off, and add to root list.

Max-damaged-Fibonacci-Heap

Max-damaged-Fibonacci-Heap has Fibonacci number nodes

Van Emde Boas Tree

description

we want to have a data structure, which can inert, delete, succ, pred, in

Open Address

for a dynamical Set S, we maintain an array A[n] only with bit 0 or 1. if i S, A[i] = 1 Set S:


1 3 4 2 5 7 8 12 11 15 14 17 20 9


Array A[]


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

1 1 1 1 1 0 1 1 1 0 1 0 0 1 1 0 1 0 0 1



min: max membership insert delete succ pred


open address + binary tree

Build a binary tree with array A[], which are repersentation of set S. Set S:


1 3 4 2 5 7 8 12 11 15 14 17 20 9


Array A[]


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

1 1 1 1 1 0 1 1 1 0 1 0 0 1 1 0 1 0 0 1



min: max membership insert delete succ pred


Open address + squart n tree

This is the same idea like with binary tree, just reduce the level to 3 we assume that the number of elements is


min: max membership insert delete succ pred


photo van Emde Boas tree

description

Array A[] in recursive stored in a tree,
this tree has many block recursively, and each block has three components,
1. integel u: indicate the elements of such block
2. point to summary, which is also a block
3. a array of lenght <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1.04em;vertical-align:-0.2397em;"></span><span class="mord sqrt"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.8003em;"><span class="svg-align" style="top:-3em;"><span class="pstrut" style="height:3em;"></span><span class="mord mathnormal" style="padding-left:0.833em;">u</span></span><span style="top:-2.7603em;"><span class="pstrut" style="height:3em;"></span><span class="hide-tail" style="min-width:0.853em;height:1.08em;"><svg xmlns="http://www.w3.org/2000/svg" width='400em' height='1.08em' viewBox='0 0 400000 1080' preserveAspectRatio='xMinYMin slice'><path d='M95,702 c-2.7,0,-7.17,-2.7,-13.5,-8c-5.8,-5.3,-9.5,-10,-9.5,-14 c0,-2,0.3,-3.3,1,-4c1.3,-2.7,23.83,-20.7,67.5,-54 c44.2,-33.3,65.8,-50.3,66.5,-51c1.3,-1.3,3,-2,5,-2c4.7,0,8.7,3.3,12,10 s173,378,173,378c0.7,0,35.3,-71,104,-213c68.7,-142,137.5,-285,206.5,-429 c69,-144,104.5,-217.7,106.5,-221 l0 -0 c5.3,-9.3,12,-14,20,-14 H400000v40H845.2724 s-225.272,467,-225.272,467s-235,486,-235,486c-2.7,4.7,-9,7,-19,7 c-6,0,-10,-1,-12,-3s-194,-422,-194,-422s-65,47,-65,47z M834 80h400000v40h-400000z'/></svg></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.2397em;"><span></span></span></span></span></span></span></span></span>, each elemenet in array point to a such block recursively

the smallest block only contains two elemenet, and it's u=2 and no sammary pointer

we start with the block, which integel u is the smallest we define: high(x) = floor low(x) = x mod index(x,y) = so x = index(high(x), low(x))

membership

Prototype_veb_member(V,x)
if V.u == 2:
  return V[x]
else return Prototype_veb_member(V.cluster[high(x)], low(x))

insert

delete

secc

pred

Van Emde Boas Tree

q implement

/* 
 * Code for van emde boas tree. Try to implement function for predecessor as
 * an exercise.
 */

#include <cmath>
#include <iostream>
#include <vector>

class vEB
{
  int u;
  int min;
  int max;
  vEB *summary;
  std::vector<vEB *> children;

  int high(int k){
    int x = std::ceil(std::sqrt(u));
    return std::floor(k / x);
  }

  int low(int k){
    int x = std::ceil(std::sqrt(u));
    return k % x;
  }

  int index(int k, int kk){
    return (k * (int)std::sqrt(u)) + kk;
  }

public:
  vEB(int U){
    // u = std::pow(std::sqrt(U), 2);
    u = U;
    min = U;
    max = -1;

    if (u <= 2){
      summary = nullptr;
      children = std::vector<vEB *> (0, nullptr);
    }
    else{
      int children_count = std::ceil(std::sqrt(u));
      int children_size = std::ceil(u / std::sqrt(u));

      summary = new vEB(children_count);
      children = std::vector<vEB *> (children_count, nullptr);
      for(int i = 0; i < children_count; ++i){
        children[i] = new vEB(children_count);
      }
    }
  }

  void insert(int k){
    if(min > max){
      min = max = k;
      return;
    }

    if(k < min){
      int temp;
      temp = min;
      min = k;
      k = temp;
    }

    if(k > max)
      max = k;

    if(u == 2){
      max = k;
      return;
    }

    int i = high(k);
    int j = low(k);

    children[i]->insert(j);

    if(children[i]->max == children[i]->min)
      summary->insert(i);
  }

  void remove(int k){
    if(min > max)
      return;

    if(min == max){
      min = u;
      max = -1;
      return;
    }

    if(u == 2){
      if(k == 1){
        if(min == 1){
          min = u;
          max = -1;
        }
        else if(min == 0)
          max = 0;
      }
      else
        if(max == 0){
          min = u;
          max = -1;
        }
        else if(max == 1)
          min = 1;
      return;
    }

    if(k == min){
      int i = summary->min;
      min = index(i, children[i]->min);
      return;
    }

    int i = high(k);
    int j = low(k);

    children[i]->remove(j);

    if(children[i]->min > children[i]->max){
      summary->remove(i);
    }

    if(k == max){
      if(summary->min > summary->max){
        max = min;
      }
      else{
        i = summary->min;
        max = index(i, children[i]->max);
      }
    }
  }

  int getMin(){
    return min;
  }
  int getMax(){
    return max;
  }

  int universe(){
    return u;
  }

  int successor(int k){
    if(k <= min)
      return min;
    else if(k > max)
      return u;

    int i = high(k);
    int j = low(k);

    if(j <= children[i]->max){
      int res = children[i]->successor(j);
      if(res >= (u / (int)std::sqrt(u)))
        return u;
      return k - j + res;
    }
    else{
      int res = children[summary->successor(i)]->min;
      if(res >= children[summary->min]->u)
        return u;
      return index(summary->successor(i), res);
    }
  }
};

int main(){
  vEB tree(1 << 4);
  std::cout << "Insert 12, 10, 13, 14\n";
  tree.insert(3);
  tree.insert(5);
  tree.insert(7);
  tree.insert(9);
  tree.insert(10);
  tree.insert(13);
  tree.insert(14);
  std::cout << "Successor of 12 is\n";
  std::cout << tree.successor(12) << '\n';
  tree.remove(13);
  std::cout << "Removing 13. Now successor of 13 is\n";
  std::cout << tree.successor(13) << '\n';
  tree.remove(14);
  std::cout << "Removing 14. Now successor of 13 is\n";
  std::cout << tree.successor(13) << '\n';
  std::cout << "16, which is universe size, means no successor.\n";

  return 0;
}

title: Parallelisum

#+STARTUP: overview

Dependence

sudo apt install openmpi-bin
sudo apt install libopenmpi-dev

Docker

old note

comands expains


docker images 查看容器 docker pull nginx 1 新增 docker run -d -p 80:80 nginx 2 开始,id, 后台 docker exec -it xxxxxx bash 前台进入, docker commit xxxxxx newname 生成新容器 docker kill -s KILL xxxxxx 关闭

Beispile

sudo docker images
sudo docker pull nginx
sudo docker run -d -p 80:80 nginx -> id:xxxxxxx
sudo docker exec -it -v /....../project:/usr/share/nginx/html xxxxxxx
build in - > local host :80  

commands

  • docker pull NAME

  • docker images

  • docker images -a

  • docker run NAME

  • docker run NAME:VERSION

  • docker run -d NAME

  • docker run -p6000:6379 -d redis

  • docker run -p6000:6379 -d --name redis-older redis

  • docker exec -it ID /bin/bash

  • docker exec -it NAME /bin/bash

<!-- -->
  • docker ps

  • docker ps -a2

  • docker start ID

  • docker stop ID

  • docker logs ID

discripation


fast delivery easy deploy and scale run more workloads easy management lightweight image No guest OS

  • Disadvanage: can not change kernel

  • Less secure than VM

  • Docker Registry hold Docker Images

  • Docker Images create Docker Container(run as instance)

  • Docker Container runs applications

  • the shared levels are readonly, and containers communicate with sockets or Restful API

delete

  • delete docker

docker ps -a // get dockerid or dockername docker stop Did/Dname docker rm Did/Dname

  • delete image docker images // get image id or image name docker rmi Iid/Iname perhaps some none name image should also be rm
  • sudo docker rm $(sudo docker ps -aq)

Singularity

build [sandbox]

build  target source
source can be singularityfile, dockerhubname, online resource,  sandbox simg file, singularity sif file

sudo singularity build singularityfile.sif singularityfile
sudo singularity build singularity.sif docker://dockerhubname


sudo singularity build --sandbox singularityfile.simg singularityfile
sudo singularity build --sandbox singularity.simg docker://dockerhubname

sudo singularity shell  singularityfile.simg

sudo singularity shell --writable singularityfile.simg

sudo singularity shell --bind /home/silin/go:/home/go  -w --nv centos-7.simg



C/C++ with OpenMP

src compile config

C-h v : org-babel-C-compiler change gcc to gcc -fopenmp

useful libary functions

omp~getthreadnum~

int main(int argc, char* argv[])
{
#pragma omp parallel
  {
    printf("omp_get_thread_num:  %d\n",  omp_get_thread_num());
  }
}
omp_get_thread_num:  0
omp_get_thread_num:  5
omp_get_thread_num:  3
omp_get_thread_num:  2
omp_get_thread_num:  7
omp_get_thread_num:  6
omp_get_thread_num:  4
omp_get_thread_num:  1

omp~getnumprocs~

int main(int argc, char* argv[])
{
  printf("omp_get_num_procs:  %d\n",  omp_get_num_procs());
  return 0;
}
omp_get_num_procs:  8

omp~getnumthreads~

int main(int argc, char* argv[])
{
#pragma omp parallel
  printf("omp_get_num_threads:  %d\n",  omp_get_num_threads());
#pragma omp parallel
#pragma omp master
  {
    printf("omp_get_num_threads:  %d\n",  omp_get_num_threads());
  }
  return 0;
}
omp_get_num_threads:  8
omp_get_num_threads:  8
omp_get_num_threads:  8
omp_get_num_threads:  8
omp_get_num_threads:  8
omp_get_num_threads:  8
omp_get_num_threads:  8
omp_get_num_threads:  8
omp_get_num_threads:  8

omp~setnumthreads~

int main()
{
  omp_set_num_threads(4);
  printf("%d\n", omp_get_num_threads( ));
#pragma omp parallel
#pragma omp master
  {
    printf("%d\n", omp_get_num_threads( ));
  }
}

1
4

omp~getwtime~

omp~getwtick~

omp~initlock~

omp~getlock~

omp~unsetlock~

omp~testlock~

omp~destroylock~

Constructor


parallel for parallel for sections parallel sections critical single barrier atomic master ordered threadprivate

Subconstructor


parivate firstprivate lastprivate reduce nowait num~threads~ schedule shared ordered copyprivate copyin default

hello world

int main(int argc, char* argv[])
{
#pragma omp parallel
  {
    printf("Hello world from thread %d\n",  omp_get_thread_num());
  }
}
Hello world from thread 0
Hello world from thread 1
Hello world from thread 4
Hello world from thread 3
Hello world from thread 5
Hello world from thread 7
Hello world from thread 6
Hello world from thread 2

num~threads~

int main(int argc, char* argv[])
{
#pragma omp parallel num_threads(6)
  {
    printf("omp_get_num_threads:  %d\n",  omp_get_num_threads());
  }
  return 0;
}
omp_get_num_threads:  6
omp_get_num_threads:  6
omp_get_num_threads:  6
omp_get_num_threads:  6
omp_get_num_threads:  6
omp_get_num_threads:  6

for

only works in one thread

int main(int argc, char* argv[])
{
  int j = 0;
#pragma omp  for
  for (j = 0; j < 8; j++){
    printf("j = %d, ThreadID = %d\n", j, omp_get_thread_num());
  }
  return 0;
}
j = 0, ThreadID = 0
j = 1, ThreadID = 0
j = 2, ThreadID = 0
j = 3, ThreadID = 0
j = 4, ThreadID = 0
j = 5, ThreadID = 0
j = 6, ThreadID = 0
j = 7, ThreadID = 0

ordered

int main(int argc, char* argv[])
{
  int j = 0;
#pragma omp parallel for ordered
  for (j = 0; j < 2; j++){
#pragma omp ordered
    {
      printf("01 ordered j = %d, ThreadID = %d\n", j, omp_get_thread_num());
    }
#pragma omp ordered
    {
      printf("02 ordered j = %d, ThreadID = %d\n", j, omp_get_thread_num());
    }
#pragma omp ordered
    {
      printf("03 ordered j = %d, ThreadID = %d\n", j, omp_get_thread_num());
    }
  }
  return 0;
}
01 ordered j = 0, ThreadID = 0
02 ordered j = 0, ThreadID = 0
03 ordered j = 0, ThreadID = 0
01 ordered j = 1, ThreadID = 1
02 ordered j = 1, ThreadID = 1
03 ordered j = 1, ThreadID = 1

parallel for

for should work with parallel

int main(int argc, char* argv[])
{
  int j = 0;
#pragma omp parallel for
  for (j = 0; j < 8; j++){
    printf("j = %d, ThreadID = %d\n", j, omp_get_thread_num());
  }
  return 0;
}
j = 0, ThreadID = 0
j = 1, ThreadID = 1
j = 2, ThreadID = 2
j = 6, ThreadID = 6
j = 5, ThreadID = 5
j = 7, ThreadID = 7
j = 3, ThreadID = 3
j = 4, ThreadID = 4
int main(int argc, char* argv[])
{
  int j = 0;
#pragma omp parallel  for
  for (j = 0; j < 8; j++){
    printf("j = %d, ThreadID = %d\n", j, omp_get_thread_num());
  }
  return 0;
}
j = 7, ThreadID = 7
j = 3, ThreadID = 3
j = 6, ThreadID = 6
j = 2, ThreadID = 2
j = 4, ThreadID = 4
j = 0, ThreadID = 0
j = 1, ThreadID = 1
j = 5, ThreadID = 5

and this can be rewrite as following, for in parallel, but can be multiple for block

int main(int argc, char* argv[])
{
  int j = 0;
#pragma omp parallel num_threads(4)
  //   #pragma omp parallel  // EQUAL TO   #pragma omp parallel num_threads(8)
  {
#pragma omp  for
    for (j = 0; j <8; j++)
      {
        printf("j = %d, ThreadID = %d\n", j, omp_get_thread_num());
      }
  }
  return 0;
}
j = 0, ThreadID = 0
j = 1, ThreadID = 0
j = 6, ThreadID = 3
j = 7, ThreadID = 3
j = 2, ThreadID = 1
j = 3, ThreadID = 1
j = 4, ThreadID = 2
j = 5, ThreadID = 2

parallel while

for should work with parallel

int main(int argc, char* argv[])
{
  int j = 0;
#pragma omp parallel num_threads(8) shared(j)
  while (j < 8){
    printf("j = %d, ThreadID = %d\n", j, omp_get_thread_num());
    j++;
  }
  return 0;
}
j = 0, ThreadID = 0
j = 0, ThreadID = 7
j = 0, ThreadID = 3
j = 2, ThreadID = 3
j = 3, ThreadID = 3
j = 4, ThreadID = 3
j = 5, ThreadID = 3
j = 6, ThreadID = 3
j = 7, ThreadID = 3
j = 0, ThreadID = 6
j = 0, ThreadID = 4
j = 0, ThreadID = 1
j = 0, ThreadID = 5
j = 1, ThreadID = 0
j = 0, ThreadID = 2

sections and section

void main(int argc, char *argv)
{
#pragma omp parallel sections
  {
#pragma omp section
    printf("section 1 ThreadId = %d\n", omp_get_thread_num());
#pragma omp section
    printf("section 2 ThreadId = %d\n", omp_get_thread_num());
#pragma omp section
    printf("section 3 ThreadId = %d\n", omp_get_thread_num());
#pragma omp section
    printf("section 4 ThreadId = %d\n", omp_get_thread_num());
  }
}
section 4 ThreadId = 0
section 3 ThreadId = 5
section 2 ThreadId = 3
section 1 ThreadId = 6

another form, parallel and sections can also be separated, and with mulitple sections block but each sections are not paralleled, but concatenated

void main(int argc, char *argv)
{
#pragma omp parallel
  {
#pragma omp sections
    {
#pragma omp section
      printf("section 1 ThreadId = %d\n", omp_get_thread_num());
#pragma omp section
      printf("section 2 ThreadId = %d\n", omp_get_thread_num());
#pragma omp section
      printf("section 3 ThreadId = %d\n", omp_get_thread_num());
    }
#pragma omp sections
    {
#pragma omp section
      printf("section 1 ThreadId = %d\n", omp_get_thread_num());
#pragma omp section
      printf("section 2 ThreadId = %d\n", omp_get_thread_num());
#pragma omp section
      printf("section 3 ThreadId = %d\n", omp_get_thread_num());
    }
  }
}
section 1 ThreadId = 3
section 2 ThreadId = 0
section 3 ThreadId = 4
section 2 ThreadId = 0
section 1 ThreadId = 1
section 3 ThreadId = 6

master

void main(int argc, char *argv)
{
#pragma omp parallel 
#pragma omp master
  {
    printf("I am the master\n");
  }
}
I am the master

private

after the block of private for, there are some wired to execute some out of parallelisum

void main(int argc, char *argv)
{
  int k = 100;
#pragma omp parallel for private(k)
  for ( k=0; k < 8; k++)
    {
      printf("k=%d\n", k);
    }
  printf("kkk = %d\n", k);
#pragma omp parallel sections
  {
#pragma omp section
    printf("kkk = %d\n", k);
  }
}
k=6
k=7
k=3
k=2
k=0
k=4
k=5
k=1
kkk = 100
kkk = 100

firstprivate

take the vaiable to Parallelisum, but not influence back

void main(int argc, char *argv)
{
  int k = 100;
#pragma omp parallel for firstprivate(k)
  for (int i=0; i < 8; i++)
    {
      k += i;
      printf("k=%d\n", k);
    }
  printf("k out of parall = %d\n", k);
}
k=103
k=107
k=100
k=104
k=106
k=102
k=105
k=101
k out of parall = 100

lastprivate

take the vaiable to Parallelisum, and influence back

void main(int argc, char *argv)
{
  int k = 100;
#pragma omp parallel for firstprivate(k) lastprivate(k)
  for (int i=0; i < 8; i++)
    {
      k += i;
      printf("k=%d\n", k);
    }
  printf("k out of parall = %d\n", k);
}
k=100
k=107
k=106
k=102
k=101
k=105
k=103
k=104
k out of parall = 107

shared

void main(int argc, char *argv)
{
  int k = 100;
  int i = 1;
#pragma omp parallel for shared(k)
  for ( i=0; i < 8; i++)
    {
      printf("k=%d\n", k);
    }
}
k=100
k=100
k=100
k=100
k=100
k=100
k=100
k=100
k = 100

reduction

void main(int argc, char *argv)
{
  int sum = 0;
  int i = 0;
#pragma omp parallel for reduction(+:sum)
  for ( i=0; i < 10; i++)
    {
      printf("omp_get_thread_num:  %d\n",  omp_get_thread_num());
      sum += i;
    }
  printf("sum is %d\n", sum);
}
omp_get_thread_num:  0
omp_get_thread_num:  0
omp_get_thread_num:  1
omp_get_thread_num:  1
omp_get_thread_num:  7
omp_get_thread_num:  2
omp_get_thread_num:  5
omp_get_thread_num:  4
omp_get_thread_num:  6
omp_get_thread_num:  3
sum is 45
void main(int argc, char *argv)
{
  int sum = 0;
  int i = 10;
#pragma omp parallel reduction(+:sum)
  {
    printf("omp_get_thread_num:  %d\n",  omp_get_thread_num());
    sum += i;
  }
  printf("sum is %d\n", sum);
}
omp_get_thread_num:  0
omp_get_thread_num:  3
omp_get_thread_num:  4
omp_get_thread_num:  2
omp_get_thread_num:  7
omp_get_thread_num:  6
omp_get_thread_num:  5
omp_get_thread_num:  1
sum is 80

default(shared)

void main(int argc, char *argv)
{
  int k = 100;
  int i = 1;
#pragma omp parallel for default(shared)
  for ( i=0; i < 8; i++)
    {
      printf("k=%d\n", k);
    }
}
k=100
k=100
k=100
k=100
k=100
k=100
k=100
k=100
i=1

schedule(static)

all iterations will be equally divied to each thread schedule(static, size): size time iterations will be drived each time

void main(int argc, char *argv)
{
  int i = 0;
#pragma omp parallel for schedule(static)
  for (i = 0; i < 24 ; i++)
    {
      printf("i=%d, thread_id=%d\n", i, omp_get_thread_num());
    }
}
i=0, thread_id=0
i=14, thread_id=7
i=15, thread_id=7
i=2, thread_id=1
i=12, thread_id=6
i=3, thread_id=1
i=18, thread_id=1
i=8, thread_id=4
i=10, thread_id=5
i=19, thread_id=1
i=9, thread_id=4
i=1, thread_id=0
i=11, thread_id=5
i=16, thread_id=0
i=13, thread_id=6
i=4, thread_id=2
i=6, thread_id=3
i=7, thread_id=3
i=22, thread_id=3
i=23, thread_id=3
i=17, thread_id=0
i=5, thread_id=2
i=20, thread_id=2
i=21, thread_id=2

schedule(dynamic)

all iterations will be dynamically divied to each thread schedule(dynamic, size): size time iterations will be drived each time

void main(int argc, char *argv)
{
  int i = 0;
#pragma omp parallel for schedule(dynamic)
  for (i = 0; i < 16 ; i++)
    {
      printf("i=%d, thread_id=%d\n", i, omp_get_thread_num());
    }
}
i=7, thread_id=7
i=8, thread_id=7
i=9, thread_id=7
i=10, thread_id=7
i=11, thread_id=7
i=12, thread_id=7
i=13, thread_id=7
i=14, thread_id=7
i=15, thread_id=7
i=0, thread_id=3
i=6, thread_id=1
i=5, thread_id=5
i=1, thread_id=6
i=2, thread_id=2
i=4, thread_id=0
i=3, thread_id=4

schedule(guided)

void main(int argc, char *argv)
{
  int i = 0;
#pragma omp parallel for schedule(guided)
  for (i = 0; i < 16 ; i++)
    {
      printf("i=%d, thread_id=%d\n", i, omp_get_thread_num());
    }
}
i=8, thread_id=0
i=11, thread_id=7
i=12, thread_id=7
i=13, thread_id=7
i=14, thread_id=7
i=15, thread_id=7
i=6, thread_id=4
i=7, thread_id=4
i=2, thread_id=2
i=3, thread_id=2
i=4, thread_id=6
i=5, thread_id=6
i=9, thread_id=1
i=10, thread_id=5
i=0, thread_id=3
i=1, thread_id=3

C/C++ with mpi

sudo apt install libopenmpi-dev

src compile config

C-h v : org-babel-C-compiler change gcc to mpicc mpirun --use-hwthread-cpus mpirun --host si-u20:8

MPI~COMMWORLD~

#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
int main(int argc, char* argv[])
{
    MPI_Init(&argc, &argv);
    int my_rank;
    MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
    printf("I am MPI process %d.\n", my_rank);
    MPI_Finalize();
    return EXIT_SUCCESS;
}
I am MPI process 0.

hello world of processor

#include <mpi.h>
#include <stdio.h>
int main(int argc, char** argv) {
    MPI_Init(NULL, NULL);
    int world_size;
    MPI_Comm_size(MPI_COMM_WORLD, &world_size);
    int world_rank;
    MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
    char processor_name[MPI_MAX_PROCESSOR_NAME];
    int name_len;
    MPI_Get_processor_name(processor_name, &name_len);
    printf("Hello world from processor %s, rank %d out of %d processors\n",
           processor_name, world_rank, world_size);

    MPI_Finalize();
}
Hello world from processor silin, rank 0 out of 1 processors

MPI~COMMCREAT~

cd ./babel
mpicc -o mpi_comm_create ./mpi_comm_create.c
mpirun --host silin:6 ./mpi_comm_create






MPI process 4 in global communicator has now rank 1 in new communicator.
MPI process 2 in global communicator has now rank 2 in new communicator.
MPI process 0 in global communicator has now rank 0 in new communicator.
MPI process 5 was not part of any group, thus did not get into a new communicator.
MPI process 1 in global communicator has now rank 1 in new communicator.
MPI process 3 in global communicator has now rank 0 in new communicator.
MPI processes 3 and 4 are in the same new communicator.
MPI processes 0 and 1 and 2 are in the same new communicator.

AllReduce

Python

Multi Thread

pure thread start

import threading

def myfunction(a,b):
    print(a*b)

thread1 = threading.Thread(target= myfunction, args=(2,3))
thread2 = threading.Thread(target= myfunction, args=(3,4))
thread1.start()
thread2.start()

thread class

rewrite [[init]{.underline}]{.underline} and run in class, which inherit class threading.Thread, and start it with start()

import threading
import time

class myThread(threading.Thread):
    def __init__(self, threadID, name, counter):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter
    def run(self):
        print("Starting " + self.name)
        self.print_time(self.name, 5, self.counter)
        print("Exiting" + self.name)
    def print_time(self, threadName, counter, delay):
        while counter:
            time.sleep(delay)
            print(f"{threadName}, {time.ctime(time.time())}")
            counter -= 1


thread1 = myThread(1, "threadone", 1)
thread2 = myThread(2, "threadtwo", 2)
thread1.start()
thread2.start()
time.sleep(1)
print("Exiting Main Thread.")

Starting threadone
Starting threadtwo
threadone, Tue Jun  7 23:53:02 2022
Exiting Main Thread.
threadtwo, Tue Jun  7 23:53:03 2022
threadone, Tue Jun  7 23:53:03 2022
threadone, Tue Jun  7 23:53:04 2022
threadtwo, Tue Jun  7 23:53:05 2022
threadone, Tue Jun  7 23:53:05 2022
threadone, Tue Jun  7 23:53:06 2022
Exitingthreadone
threadtwo, Tue Jun  7 23:53:07 2022
threadtwo, Tue Jun  7 23:53:09 2022
threadtwo, Tue Jun  7 23:53:11 2022
Exitingthreadtwo

thread with Lock

import threading
import time

myLock = threading.Lock()
class myThread(threading.Thread):
    def __init__(self, threadID, name, counter):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter
    def run(self):
        print("Starting " + self.name)
        myLock.acquire()
        self.print_time(self.name, 5, self.counter)
        myLock.release()
        print("Exiting" + self.name)
    def print_time(self, threadName, counter, delay):
        while counter:
            time.sleep(delay)
            print(f"{threadName}, {time.ctime(time.time())}")
            counter -= 1

thread1 = myThread(1, "threadone", 1)
thread2 = myThread(2, "threadtwo", 2)
thread1.start()
thread2.start()
time.sleep(1)
print("Exiting Main Thread.")

Starting threadone
Starting threadtwo
threadone, Tue Jun  7 23:53:58 2022
Exiting Main Thread.
threadone, Tue Jun  7 23:53:59 2022
threadone, Tue Jun  7 23:54:00 2022
threadone, Tue Jun  7 23:54:01 2022
threadone, Tue Jun  7 23:54:02 2022
Exitingthreadone
threadtwo, Tue Jun  7 23:54:04 2022
threadtwo, Tue Jun  7 23:54:06 2022
threadtwo, Tue Jun  7 23:54:08 2022
threadtwo, Tue Jun  7 23:54:10 2022
threadtwo, Tue Jun  7 23:54:12 2022
Exitingthreadtwo

Multi processing

pure multi process start

import multiprocessing
def myfunction(a,b):
    print(a*b)
process1 = multiprocessing.Process(target=myfunction, args=(2,9))
process2 = multiprocessing.Process(target=myfunction, args=(3,4))
process1.start()
process2.start()
18
12

multi process differ from multi threading

import multiprocessing
import threading
import random

def myfunction ():
    result.append(random.randint(1,10))
    ####processing
result = []
process1 = multiprocessing.Process(target=myfunction)
process2 = multiprocessing.Process(target=myfunction)
process1.start()
process2.start()
process1.join()
process2.join()
print("result of multiprocessing", result)
####threading
result = []
thread1 = threading.Thread(target=myfunction)
thread2 = threading.Thread(target=myfunction)
thread1.start()
thread2.start()
thread1.join()
thread2.join()
print("result of multi threading", result)
result of multiprocessing []
result of multi threading [1, 2]

Pool

  1. apply

    import multiprocessing as mp
    def myfunction(a, b):
        return a*b
    
    pool = mp.Pool(mp.cpu_count())
    result = [ pool.apply(myfunction, args=(a, 2)) for a in range(1, 100) ]
    pool.close()
    print(result)
    
    
    [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100, 102, 104, 106, 108, 110, 112, 114, 116, 118, 120, 122, 124, 126, 128, 130, 132, 134, 136, 138, 140, 142, 144, 146, 148, 150, 152, 154, 156, 158, 160, 162, 164, 166, 168, 170, 172, 174, 176, 178, 180, 182, 184, 186, 188, 190, 192, 194, 196, 198]
    
  2. map

    import multiprocessing as mp
    def myfunction(a):
        return a*a
    
    pool = mp.Pool(mp.cpu_count())
    result =  pool.map(myfunction, [a for a in range(1, 100)]) 
    pool.close()
    print(result)
    
    
    [1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484, 529, 576, 625, 676, 729, 784, 841, 900, 961, 1024, 1089, 1156, 1225, 1296, 1369, 1444, 1521, 1600, 1681, 1764, 1849, 1936, 2025, 2116, 2209, 2304, 2401, 2500, 2601, 2704, 2809, 2916, 3025, 3136, 3249, 3364, 3481, 3600, 3721, 3844, 3969, 4096, 4225, 4356, 4489, 4624, 4761, 4900, 5041, 5184, 5329, 5476, 5625, 5776, 5929, 6084, 6241, 6400, 6561, 6724, 6889, 7056, 7225, 7396, 7569, 7744, 7921, 8100, 8281, 8464, 8649, 8836, 9025, 9216, 9409, 9604, 9801]
    
  3. starmap

    import multiprocessing as mp
    def myfunction(a, b):
        return a*b
    
    pool = mp.Pool(mp.cpu_count())
    result = pool.starmap(myfunction, [(a, 2) for a in range(1, 100)] ) 
    pool.close()
    print(result)
    
    
    [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100, 102, 104, 106, 108, 110, 112, 114, 116, 118, 120, 122, 124, 126, 128, 130, 132, 134, 136, 138, 140, 142, 144, 146, 148, 150, 152, 154, 156, 158, 160, 162, 164, 166, 168, 170, 172, 174, 176, 178, 180, 182, 184, 186, 188, 190, 192, 194, 196, 198]
    
  4. apply~async~

    import multiprocessing as mp
    def myfunction(a, b):
        return a*b
    
    pool = mp.Pool(mp.cpu_count())
    result = [ pool.apply_async(myfunction, args=(a, 2)) for a in range(1, 100)]
    result = [r.get() for r in result]
    pool.close()
    print(result)
    
    
    [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100, 102, 104, 106, 108, 110, 112, 114, 116, 118, 120, 122, 124, 126, 128, 130, 132, 134, 136, 138, 140, 142, 144, 146, 148, 150, 152, 154, 156, 158, 160, 162, 164, 166, 168, 170, 172, 174, 176, 178, 180, 182, 184, 186, 188, 190, 192, 194, 196, 198]
    
  5. apply~async~ with callback, must use wait

    import multiprocessing as mp
    results = []
    def myfunction(a, b):
        return a*b
    def collect_result(result):
        global results
        results.append(result)
    
    pool = mp.Pool(mp.cpu_count())
    for a in range(1, 100):
        r = pool.apply_async(myfunction, args=(a, 2), callback=collect_result)
        r.wait()
        pool.close()
    
    print(results)
    

map

import time
import concurrent.futures

def do_something(n):
    print(f"sleeping {n} seconds")
    time.sleep(n)
    return f"Done {n} seconds sleep"


with concurrent.futures.ProcessPoolExecutor() as executor:
    secs = [5,4,3,2,1]
    results = executor.map(do_something, secs)

    for result in results:
        print(result)

sleeping 1 seconds
sleeping 2 seconds
sleeping 3 seconds
sleeping 4 seconds
sleeping 5 seconds
Done 5 seconds sleep
Done 4 seconds sleep
Done 3 seconds sleep
Done 2 seconds sleep
Done 1 seconds sleep

Python with mpi

send & recv

from mpi4py import MPI
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
if rank == 0:
 data = {'a': 1, 'b': 2, 'c':'test string'}
 comm.send(data,dest=1,tag=11)
elif rank == 1:
 data = comm.recv(source=0,tag=11)
 print(data)  
mpirun -n 2 python3 ./babel/mpi_python_example01.py
{'a': 1, 'b': 2, 'c': 'test string'}

Send & Recv

from mpi4py import MPI
import numpy
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
if rank == 0:
 data = numpy.arange(100, dtype=numpy.float)
 comm.Send(data,dest=1,tag=11)
elif rank == 1:
 data = numpy.empty(100,dtype=numpy.float)
 comm.Recv(data, source=0,tag=11)
 print(data)
mpirun -n 2 python3 ./babel/mpi_python_example02.py
[ 0.  1.  2.  3.  4.  5.  6.  7.  8.  9. 10. 11. 12. 13. 14. 15. 16. 17.
 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35.
 36. 37. 38. 39. 40. 41. 42. 43. 44. 45. 46. 47. 48. 49. 50. 51. 52. 53.
 54. 55. 56. 57. 58. 59. 60. 61. 62. 63. 64. 65. 66. 67. 68. 69. 70. 71.
 72. 73. 74. 75. 76. 77. 78. 79. 80. 81. 82. 83. 84. 85. 86. 87. 88. 89.
 90. 91. 92. 93. 94. 95. 96. 97. 98. 99.]

Bcast

with map bcast

from mpi4py import MPI
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
if rank == 0:
 data = {'key1' : [7, 2.72, 2+3j], 'key2' : ( 'abc', 'xyz')}
else:
 data = None
data = comm.bcast(data, root=0)
print(data)  
mpirun -n 3 python3 ./babel/mpi_python_example03.py
{'key1': [7, 2.72, (2+3j)], 'key2': ('abc', 'xyz')}
{'key1': [7, 2.72, (2+3j)], 'key2': ('abc', 'xyz')}
{'key1': [7, 2.72, (2+3j)], 'key2': ('abc', 'xyz')}

with array Bcast

from mpi4py import MPI
import numpy as np
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
if rank == 0:
 data = np.arange(100, dtype='i')
else:
 data = np.empty(100, dtype='i')
comm.Bcast(data, root=0)
for i in range(100):
 assert data[i] == i

mpirun -n 3 python3 ./babel/mpi_python_example07.py

scatter

with number

from mpi4py import MPI
comm = MPI.COMM_WORLD
size = comm.Get_size()
rank = comm.Get_rank()
if rank == 0:
 data = [(i+1)**2 for i in range(size)]
else:
 data = None
data = comm.scatter(data, root=0)
assert data == (rank+1)**2

mpirun -n 4 python3 ./babel/mpi_python_example04.py

with array

from mpi4py import MPI
import numpy as np
comm = MPI.COMM_WORLD
size = comm.Get_size()
rank = comm.Get_rank()
sendbuf = None
if rank == 0:
 sendbuf = np.empty([size, 100], dtype='i')
 sendbuf.T[:,:] = range(size)
recvbuf = np.empty(100, dtype='i')
comm.Scatter(sendbuf, recvbuf, root=0)
assert np.allclose(recvbuf, rank)  
mpirun --host si-u20:6 python3 ./babel/mpi_python_example08.py

Gather

with number gather

from mpi4py import MPI
comm = MPI.COMM_WORLD
size = comm.Get_size()
rank = comm.Get_rank()
data = (rank+1)**2
data = comm.gather(data, root=0)
if rank == 0:
 for i in range(size):
  assert data[i] == (i+1)**2
else:
 assert data is None

mpirun --host si-u20:8 python3 ./babel/mpi_python_example05.py
8
8
8
8
8
8
8
8

with array Gather

from mpi4py import MPI
import numpy as np
comm = MPI.COMM_WORLD
size = comm.Get_size()
rank = comm.Get_rank()
sendbuf = np.zeros(100, dtype='i') + rank
recvbuf = None
if rank == 0:
 recvbuf = np.empty([size, 100], dtype='i')
comm.Gather(sendbuf, recvbuf, root=0)
if rank == 0:
 for i in range(size):
  assert np.allclose(recvbuf[i,:], i)
mpirun -n 4 python3 ./babel/mpi_python_example09.py

Dynamic Process Management

from mpi4py import MPI
import numpy
import sys
comm = MPI.COMM_SELF.Spawn(sys.executable,
                           args=['./mpi_python_example_server.py'],
                           maxprocs=2)
N = numpy.array(100, 'i')
comm.Bcast([N, MPI.INT], root=MPI.ROOT)
PI = numpy.array(0.0, 'd')
comm.Reduce(None, [PI, MPI.DOUBLE],
            op=MPI.SUM, root=MPI.ROOT)
print(PI)
comm.Disconnect()

from mpi4py import MPI
import numpy
comm = MPI.Comm.Get_parent()
size = comm.Get_size()
rank = comm.Get_rank()
N = numpy.array(0, dtype='i')
comm.Bcast([N, MPI.INT], root=0)
h = 1.0 / N; s = 0.0
for i in range(rank, N, size):
 x = h * (i + 0.5)
 s += 4.0 / (1.0 + x**2)
PI = numpy.array(s * h, dtype='d')
comm.Reduce([PI, MPI.DOUBLE], None, op=MPI.SUM, root=0)
comm.Disconnect()


mpirun --host si-u20:4 python3 ./babel/mpi_python_example_client.py

Go

go chan

package main
import (
        "fmt"
        "time"
)
func main() {
        var times int
        go func() {
                for {
                }
        }()
        go func() {
                for {
                }
        }()
        go func() {
                for {
                }
        }()
        go func() {
                for {
                }
        }()
        go func() {
                for {
                }
        }()
        for times = 0; times <= 10; times++ {
                fmt.Println("tick", times)
                time.Sleep(time.Second)
        }
}

package main
import (
        "fmt"
        "time"
)
func main() {
        ch1 := make(chan int)
        go func (ch chan int){
                for{
                        select {
                        case <- ch:
                                fmt.Println("get it")
                        default:
                                fmt.Println("still not")
                        }
                }
        }(ch1)

        time.Sleep(time.Second)
        ch1 <- 2;
}

Go with mpi

cpuNum

package main
import (
    "fmt"
    "runtime"
)

func main() {
    cpuNum := runtime.NumCPU()
    fmt.Println("cpu number is :", cpuNum)
    runtime.GOMAXPROCS(cpuNum)
}
cpu number is : 8
go build ./babel/go_mpi_cpuNum.go && ./babel/go_mpi_cpuNum
cpu number is : 8

IsOn

package main

import (
        "fmt"
        mpi "github.com/sbromberger/gompi"
)
func main() {
        ison := mpi.IsOn()
        if ison {
                fmt.Println("ison is on")
        } else {
                fmt.Println("ison is  not on")
        }
        mpi.Start(true)
        ison = mpi.IsOn()
        if ison {
                fmt.Println("ison is on")
        } else {
                fmt.Println("ison is  not on ")
        }
        mpi.Stop()
}
cd babel
go mod tidy
go build ./go_mpi_ison.go && ./go_mpi_ison
ison is  not on
ison is on

WorldRank

package main

import (
        "fmt"
        mpi "github.com/sbromberger/gompi"
)
func main() {
        mpi.Start(true)
        rank := mpi.WorldRank()
        fmt.Println("rank is", rank)
        mpi.Stop()
}
cd babel
go mod tidy
go build ./go_mpi_WorldRank.go && mpirun --use-hwthread-cpus ./go_mpi_WorldRank
rank is 0
rank is 1
rank is 2
rank is 3
rank is 5
rank is 7
rank is 6
rank is 4

WorldSize

package main

import (
        "fmt"
        mpi "github.com/sbromberger/gompi"
)
func main() {
        mpi.Start(true)
        size := mpi.WorldSize()
        fmt.Println("rank is", size)
        mpi.Stop()
}
cd babel
go mod tidy
go build ./go_mpi_WorldSize.go && mpirun --use-hwthread-cpus ./go_mpi_WorldSize
rank is 8
rank is 8
rank is 8
rank is 8
rank is 8
rank is 8
rank is 8
rank is 8

NewCommunicator

package main

import (
        "fmt"
        mpi "github.com/sbromberger/gompi"
)
func main() {
        mpi.Start(true)
        var ranks []int
        newComm := mpi.NewCommunicator(ranks)
        fmt.Println("newComm.Size() is :", newComm.Size())
        fmt.Println("newComm.Rank() is :", newComm.Rank())
        mpi.Stop()
}
cd babel
go mod tidy
go build ./go_mpi_NewCommunicator.go && mpirun --use-hwthread-cpus ./go_mpi_NewCommunicator
newComm.Size() is : 8
newComm.Rank() is : 1
newComm.Size() is : 8
newComm.Rank() is : 7
newComm.Size() is : 8
newComm.Rank() is : 2
newComm.Size() is : 8
newComm.Size() is : 8
newComm.Rank() is : 0
newComm.Rank() is : 4
newComm.Size() is : 8
newComm.Rank() is : 3
newComm.Size() is : 8
newComm.Rank() is : 5
newComm.Size() is : 8
newComm.Rank() is : 6
package main

import (
        "fmt"
        mpi "github.com/sbromberger/gompi"
)
func main() {
        mpi.Start(true)
        var ranks []int = []int{0,1,2,3}
        newComm := mpi.NewCommunicator(ranks)
        fmt.Println("newComm.Size() is :", newComm.Size())
        fmt.Println("newComm.Rank() is :", newComm.Rank())
        mpi.Stop()
}
cd babel
go build ./go_mpi_NewCommunicator_withranks.go && mpirun --host si-u20:4 ./go_mpi_NewCommunicator_withranks
newComm.Size() is : 4
newComm.Rank() is : 0
newComm.Size() is : 4
newComm.Rank() is : 1
newComm.Size() is : 4
newComm.Rank() is : 2
newComm.Size() is : 4
newComm.Rank() is : 3

SendInt32 && RecvInt32

package main
import (
        "fmt"
        mpi "github.com/sbromberger/gompi"
)
func main() {
        mpi.Start(true)
        fmt.Println()
        var ranks []int 
        newComm := mpi.NewCommunicator(ranks)
        if newComm.Rank() == 0 {
                var data int32 = 60
                newComm.SendInt32(data, 1, 10)
        }
        if newComm.Rank() == 1 {
                data, _ := newComm.RecvInt32(0, 10)
                fmt.Println(data)
        }
        mpi.Stop()
}
cd babel
go mod tidy
go build ./go_mpi_SendInt32.go
mpirun --use-hwthread-cpus ./go_mpi_SendInt32






60


SendInt32s && RecvInt32s

package main

import (
        "fmt"

        mpi "github.com/sbromberger/gompi"
)
func main() {
        mpi.Start(true)
        fmt.Println()
        var ranks []int 
        newComm := mpi.NewCommunicator(ranks)
        if newComm.Rank() == 0 {
                var data []uint32 = []uint32{1, 2, 3, 4}
                newComm.SendUInt32s(data, 1, 10)
        }
        if newComm.Rank() == 1 {
                data, _ := newComm.RecvInt32s(0, 10)
                fmt.Println(data)
        }
        mpi.Stop()
}
cd babel
go mod tidy
go build ./go_mpi_SendUInt32s.go
mpirun --host si:6 ./go_mpi_SendUInt32s






[1 2 3 4]

SendString && RecvString

package main

import (
        "fmt"

        mpi "github.com/sbromberger/gompi"
)
func main() {
        mpi.Start(true)
        fmt.Println()
        var ranks []int
        newComm := mpi.NewCommunicator(ranks)
        if newComm.Rank() == 0 {
                str1 := "str11"
                newComm.SendString("nihao", 1, 11)
                newComm.SendString(str1, 1, 10)
        }
        // better with differ tags, but with the same tags works here also
        if newComm.Rank() == 1 {
                nihao, _ := newComm.RecvString(0, 11)
                str1, _ := newComm.RecvString(0, 10)
                fmt.Println(nihao)
                fmt.Println(str1)
        }
        mpi.Stop()
}

cd babel
go mod tidy
go build ./go_mpi_SendString.go
mpirun -n 2 ./go_mpi_SendString


nihao
str11

ReduceInt32s

package main

import (
        "fmt"

        mpi "github.com/sbromberger/gompi"
)
func main() {
        mpi.Start(true)
        fmt.Println()
        var ranks []int
        newComm := mpi.NewCommunicator(ranks)
        var dest []int32 = []int32{0, 0, 0, 0}
        var send []int32 = []int32{7, 2, 3, 4}
        newComm.ReduceInt32s(dest, send, mpi.OpSum, 0)
        if newComm.Rank() == 0 {
                fmt.Println(dest)
        }
        mpi.Stop()
}
cd babel
go mod tidy
go build ./go_mpi_ReduceInt32s.go
mpirun -n 4 ./go_mpi_ReduceInt32s




[28 8 12 16]

AllreduceInt64s

package main
import (
        "fmt"
        mpi "github.com/sbromberger/gompi"
)
func main() {
        mpi.Start(true)
        var ranks []int
        newComm := mpi.NewCommunicator(ranks)
        var dest []int64 = []int64{0, 0}
        var send []int64 = []int64{20 * int64(newComm.Rank()), 2}
        newComm.AllreduceInt64s(dest, send, mpi.OpSum, 0)
        if newComm.Rank() == 0 {
                fmt.Println(dest)
        }
        mpi.Stop()
}
cd babel
go mod tidy
go build ./go_mpi_AllreduceInt64s.go
mpirun -n 4 ./go_mpi_AllreduceInt64s

[120 8]

BcastInt64s

package main
import (
        "fmt"
        mpi "github.com/sbromberger/gompi"
)

func main() {
        mpi.Start(true)
        var ranks []int
        newComm := mpi.NewCommunicator(ranks)
        var send []int64 = []int64{10 + int64(newComm.Rank())}
        fmt.Printf("process %v now has original value of %v from main process  \n", newComm.Rank(), send)
        newComm.BcastInt64s(send, 0)
        if newComm.Rank() != 0 {
           fmt.Printf("process %v now has bordcasted value of %v from main process  \n", newComm.Rank(), send)
        }
        mpi.Stop()
}

cd babel
go mod tidy
go build ./go_mpi_BcastInt64s.go
mpirun -n 4 ./go_mpi_BcastInt64s
process 3 now has original value of [13] from main process  
process 1 now has original value of [11] from main process  
process 0 now has original value of [10] from main process  
process 2 now has original value of [12] from main process  
process 1 now has bordcasted value of [10] from main process  
process 2 now has bordcasted value of [10] from main process  
process 3 now has bordcasted value of [10] from main process  

distributed-client

package main

import (
        "fmt"
        "math/rand"
        "time"

        mpi "github.com/sbromberger/gompi"
)

func main(){
        mpi.Start(true)
        var ranks []int
        newComm := mpi.NewCommunicator(ranks)
        fmt.Println("rank is ", newComm.Rank())
        start := []float64{0, 0, 0}
        ends := []float64{0, 0, 0}
        newComm.BcastFloat64s(start, 0)

        if newComm.Rank() != 0 {
                for { 
                        for i, x := range start {
                                start[i] = x+float64(rand.Intn(10))
                        }
                        time.Sleep(time.Second)
                        fmt.Printf("process %v now has value of %v from main process \n", newComm.Rank(), start)
                        newComm.SendFloat64s(start, 0, newComm.Rank())
                        start, _ = newComm.RecvFloat64s(0, newComm.Rank())
                }
        }

        if newComm.Rank() == 0 {
                go func (){
                        for { 
                                start, _ := newComm.RecvFloat64s(1, 1)
                                for i, _ := range start {
                                        start[i] = start[i] * ends[i]
                                }
                                newComm.SendFloat64s(start, 1, 1)
                        }
                }()

                go func (){
                        for { 
                                start, _ := newComm.RecvFloat64s(2, 2)
                                for i, _ := range start {
                                        start[i] = start[i] * ends[i]
                                }
                                newComm.SendFloat64s(start, 2, 2)
                        }
                }()

                go func (){
                        for { 
                                start, _ := newComm.RecvFloat64s(3, 3)
                                for i, _ := range start {
                                        start[i] = start[i] * ends[i]
                                }
                                newComm.SendFloat64s(start, 3, 3)
                        }
                }()
        }
        mpi.Stop()
}


cd babel
go mod tidy
go build ./go_mpi_distributed-client.go
mpirun -n 4 ./go_mpi_distributed-client

Distributed learning server client

package main

import (
    "fmt"
    "sync"
    "time"

    mpi "github.com/sbromberger/gompi"
)

func mainn(){
    mpi.Start(true)
    var ranks []int
    newComm := mpi.NewCommunicator(ranks)

    start := []float64{float64(newComm.Rank()), float64(newComm.Rank()), float64(newComm.Rank())}
    //  ends := []float64{0, 0, 0}
    var m sync.Mutex
    ch1 := make(chan []float64, 3)
    ch2 := make(chan []float64, 3)
    ch3 := make(chan []float64, 3)
    fmt.Printf("Orignal: %v now has value of %v from main process \n", newComm.Rank(), start)

    newComm.BcastFloat64s(start, 0)

    if newComm.Rank() == 0 {
        go func (ch0 chan []float64){
            for { 
                start, _ := newComm.RecvFloat64s(1, 1)
                ch0 <- start
            }
        }(ch1)

        go func (ch0 chan []float64){
            for { 
                start, _ := newComm.RecvFloat64s(2, 2)
                ch0 <- start;
            }
        }(ch2)

        go func (ch0 chan []float64){
            for { 
                start, _ := newComm.RecvFloat64s(3, 3)
                ch0 <- start;
            }
        }(ch3)
    }

    func (newComm *mpi.Communicator ) {
        for {
            select {
            case <- ch1:
                m.Lock()
                data := <- ch1
                for i, _ := range start {
                    start[i] = start[i] * data[i]
                }
                m.Unlock()
                newComm.BcastFloat64s(start, 0)
                fmt.Printf("From process %v now has value of %v from main process \n", data, start)
            case <- ch2:
                m.Lock()
                data := <- ch2
                for i, _ := range start {
                    start[i] = start[i] * data[i]
                }
                m.Unlock()
                newComm.BcastFloat64s(start, 0)
                fmt.Printf("From process %v now has value of %v from main process \n", data, start)
            case <- ch3:
                m.Lock()
                data := <- ch3
                for i, _ := range start {
                    start[i] = start[i] * data[i]
                }
                m.Unlock()
                newComm.BcastFloat64s(start, 0)
                fmt.Printf("From process %v now has value of %v from main process \n", data, start)
                default:
            }
        }
    }(newComm)


    if newComm.Rank() != 0 {
        for {
            time.Sleep(time.Second*2)
            fmt.Printf("PROCESS: %v now has value of %v from main process \n", newComm.Rank(), start)
            for i, x := range start {
                start[i] = x+1
            }
            newComm.SendFloat64s(start, 0, newComm.Rank())
        }
    }

    mpi.Stop()
}


Distributed learning server client one to one

package main

import (
    "fmt"
    "time"

    mpi "github.com/sbromberger/gompi"
)


func main(){
    mpi.Start(true)
    var ranks []int
    newComm := mpi.NewCommunicator(ranks)
    ch0 := make(chan int)

    start := []float64{float64(newComm.Rank()), float64(newComm.Rank()), float64(newComm.Rank())}
    fmt.Printf("Orignal: %v now has value of %v from main process \n", newComm.Rank(), start)

    go func (newComm *mpi.Communicator, ch0 chan int) {
        time.Sleep(time.Second*1)
        for {
            select {
            case data := <- ch0:
                for i, _ := range start {
                    start[i] = start[i] * float64(data)
                }
                fmt.Printf("From server: %v now has value of %v from main process \n", newComm.Rank(), start)
                newComm.BcastFloat64s(start, 0)
            case <- time.After(time.Minute):
                fmt.Println("Time out")
            }
        }
    }(newComm, ch0)

    if newComm.Rank() == 0 {
        go func (ch0 chan int ){
            for {
                newComm.RecvFloat64s(1, 1)
                ch0 <- 1;
            }
        }(ch0)
    }

    if newComm.Rank() == 1 {
        for {
            time.Sleep(time.Second*2)
            for i, _ := range start {
                start[i] = start[i] + 2
            }
            fmt.Printf("From client: %v now has value of %v from main process \n", newComm.Rank(), start)
            newComm.SendFloat64s(start, 0, newComm.Rank())
        }
    }

    time.Sleep(time.Minute)
    mpi.Stop()
}


GPGPU

get variables

#include <stdio.h>
#include <cuda.h>
#include <assert.h>
#include <cuda_runtime.h>
#include <curand_kernel.h>
#define N 32
__global__ void add(
                    int *dthreadIdx_x,
                    int *dthreadIdx_y,
                    int *dthreadIdx_z,
                    int *dblockIdx_x,
                    int *dblockIdx_y,
                    int *dblockIdx_z,
                    int *dblockDim_x,
                    int *dblockDim_y,
                    int *dblockDim_z,
                    int *dgridDim_x,
                    int *dgridDim_y,
                    int *dgridDim_z){
  *dthreadIdx_x = threadIdx.x;
  *dthreadIdx_y = threadIdx.y;
  *dthreadIdx_z = threadIdx.z;
  *dblockIdx_x = blockIdx.x;
  *dblockIdx_y = blockIdx.y;
  *dblockIdx_z = blockIdx.z;
  *dblockDim_x = blockDim.x;
  *dblockDim_y = blockDim.y;
  *dblockDim_z = blockDim.z;
  *dgridDim_x = gridDim.x;
  *dgridDim_y = gridDim.y;
  *dgridDim_z = gridDim.z;
}
int main()
{
  int threadIdx_x = 0;
  int threadIdx_y = 0;
  int threadIdx_z = 0;
  int blockIdx_x = 0;
  int blockIdx_y = 0;
  int blockIdx_z = 0;
  int blockDim_x = 0;
  int blockDim_y = 0;
  int blockDim_z = 0;
  int gridDim_x = 0;
  int gridDim_y = 0;
  int gridDim_z = 0;

  int *dthreadIdx_x;
  int *dthreadIdx_y;
  int *dthreadIdx_z;
  int *dblockIdx_x;
  int *dblockIdx_y;
  int *dblockIdx_z;
  int *dblockDim_x;
  int *dblockDim_y;
  int *dblockDim_z;
  int *dgridDim_x;
  int *dgridDim_y;
  int *dgridDim_z;

  cudaMalloc((void **)&dthreadIdx_x, sizeof(int));
  cudaMalloc((void **)&dthreadIdx_y, sizeof(int));
  cudaMalloc((void **)&dthreadIdx_z, sizeof(int));
  cudaMalloc((void **)&dblockIdx_x, sizeof(int));
  cudaMalloc((void **)&dblockIdx_y, sizeof(int));
  cudaMalloc((void **)&dblockIdx_z, sizeof(int));
  cudaMalloc((void **)&dblockDim_x, sizeof(int));
  cudaMalloc((void **)&dblockDim_y, sizeof(int));
  cudaMalloc((void **)&dblockDim_z, sizeof(int));
  cudaMalloc((void **)&dgridDim_x, sizeof(int));
  cudaMalloc((void **)&dgridDim_y, sizeof(int));
  cudaMalloc((void **)&dgridDim_z, sizeof(int));

  dim3 BlockPerGrid(1, 1, 1);
  dim3 ThreadsPerBlock(N, N, 1);
  add <<< BlockPerGrid, ThreadsPerBlock >>>(
                                            dthreadIdx_x,
                                            dthreadIdx_y,
                                            dthreadIdx_z,
                                            dblockIdx_x,
                                            dblockIdx_y,
                                            dblockIdx_z,
                                            dblockDim_x,
                                            dblockDim_y,
                                            dblockDim_z,
                                            dgridDim_x,
                                            dgridDim_y,
                                            dgridDim_z
                                            );
  cudaMemcpy(&threadIdx_x,dthreadIdx_x, sizeof(int), cudaMemcpyDeviceToHost);
  printf("threadIdx_x is %d \n", threadIdx_x);
  cudaMemcpy(&threadIdx_y,dthreadIdx_y, sizeof(int), cudaMemcpyDeviceToHost);
  printf("threadIdx_y is %d \n", threadIdx_y);
  cudaMemcpy(&threadIdx_z,dthreadIdx_z, sizeof(int), cudaMemcpyDeviceToHost);
  printf("threadIdx_z is %d \n", threadIdx_z);

  cudaMemcpy(&blockIdx_x, dblockIdx_x, sizeof(int), cudaMemcpyDeviceToHost);
  printf("blockIdx_x is %d \n", blockIdx_x);
  cudaMemcpy(&blockIdx_y, dblockIdx_y, sizeof(int), cudaMemcpyDeviceToHost);
  printf("blockIdx_y is %d \n", blockIdx_y);
  cudaMemcpy(&blockIdx_z, dblockIdx_z, sizeof(int), cudaMemcpyDeviceToHost);
  printf("blockIdx_z is %d \n", blockIdx_z);


  cudaMemcpy(&blockDim_x, dblockDim_x, sizeof(int), cudaMemcpyDeviceToHost);
  printf("blockDim_x is %d \n", blockDim_x);
  cudaMemcpy(&blockDim_y, dblockDim_y, sizeof(int), cudaMemcpyDeviceToHost);
  printf("blockDim_y is %d \n", blockDim_y);
  cudaMemcpy(&blockDim_z, dblockDim_z, sizeof(int), cudaMemcpyDeviceToHost);
  printf("blockDim_z is %d \n", blockDim_z);

  cudaMemcpy(&gridDim_x, dgridDim_x, sizeof(int), cudaMemcpyDeviceToHost);
  printf("gridDim_x is %d \n", gridDim_x);
  cudaMemcpy(&gridDim_y, dgridDim_y, sizeof(int), cudaMemcpyDeviceToHost);
  printf("gridDim_y is %d \n", gridDim_y);
  cudaMemcpy(&gridDim_z, dgridDim_z, sizeof(int), cudaMemcpyDeviceToHost);
  printf("gridDim_z is %d \n", gridDim_z);

  return 0;
}
cd babel
nvcc gpu_get_variables.cu -o gpu_get_variables
./gpu_get_variables

Addition dim 1

without parallelism

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <assert.h>
#include <cuda.h>
#include <cuda_runtime.h>

#define N 10000000
#define MAX_ERR 1e-6

__global__ void vector_add(float *out, float *a, float *b, int n) {
  for(int i = 0; i < n; i ++){
    out[i] = a[i] + b[i];
  }
}

int main(){
  float *a, *b, *out;
  float *d_a, *d_b, *d_out; 

  // Allocate host memory
  a   = (float*)malloc(sizeof(float) * N);
  b   = (float*)malloc(sizeof(float) * N);
  out = (float*)malloc(sizeof(float) * N);

  // Initialize host arrays
  for(int i = 0; i < N; i++){
    a[i] = 1.0f;
    b[i] = 2.0f;
  }

  // Allocate device memory
  cudaMalloc((void**)&d_a, sizeof(float) * N);
  cudaMalloc((void**)&d_b, sizeof(float) * N);
  cudaMalloc((void**)&d_out, sizeof(float) * N);

  // Transfer data from host to device memory
  cudaMemcpy(d_a, a, sizeof(float) * N, cudaMemcpyHostToDevice);
  cudaMemcpy(d_b, b, sizeof(float) * N, cudaMemcpyHostToDevice);

  // Executing kernel 
       vector_add<<<1,1>>>(d_out, d_a, d_b, N);

  // Transfer data back to host memory
  cudaMemcpy(out, d_out, sizeof(float) * N, cudaMemcpyDeviceToHost);

  // Verification
  for(int i = 0; i < N; i++){
    assert(fabs(out[i] - a[i] - b[i]) < MAX_ERR);
  }
  printf("out[0] = %f\n", out[0]);
  printf("PASSED\n");

  // Deallocate device memory
  cudaFree(d_a);
  cudaFree(d_b);
  cudaFree(d_out);

  // Deallocate host memory
  free(a); 
  free(b); 
  free(out);
}

cd babel
nvcc gpu_vector_add_withoutpara.cu -o gpu_vector_add_withoutpara
./gpu_vector_add_withoutpara
out[0] = 3.000000
PASSED

dim 1, grid 1, block 256 N10000000

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <assert.h>
#include <cuda.h>
#include <cuda_runtime.h>

#define N 10000000
#define MAX_ERR 1e-6

__global__ void vector_add(float *out, float *a, float *b, int n) {
  int index = threadIdx.x;
  int stride = blockDim.x;

  for(int i = index; i < n; i += stride){
    out[i] = a[i] + b[i];
  }
}

int main(){
  float *a, *b, *out;
  float *d_a, *d_b, *d_out; 

  // Allocate host memory
  a   = (float*)malloc(sizeof(float) * N);
  b   = (float*)malloc(sizeof(float) * N);
  out = (float*)malloc(sizeof(float) * N);

  // Initialize host arrays
  for(int i = 0; i < N; i++){
    a[i] = 1.0f;
    b[i] = 2.0f;
  }

  // Allocate device memory 
  cudaMalloc((void**)&d_a, sizeof(float) * N);
  cudaMalloc((void**)&d_b, sizeof(float) * N);
  cudaMalloc((void**)&d_out, sizeof(float) * N);

  // Transfer data from host to device memory
  cudaMemcpy(d_a, a, sizeof(float) * N, cudaMemcpyHostToDevice);
  cudaMemcpy(d_b, b, sizeof(float) * N, cudaMemcpyHostToDevice);

  // Executing kernel 
  vector_add<<<1,256>>>(d_out, d_a, d_b, N);

  // Transfer data back to host memory
  cudaMemcpy(out, d_out, sizeof(float) * N, cudaMemcpyDeviceToHost);

  // Verification
  for(int i = 0; i < N; i++){
    assert(fabs(out[i] - a[i] - b[i]) < MAX_ERR);
  }

  printf("PASSED\n");

  // Deallocate device memory
  cudaFree(d_a);
  cudaFree(d_b);
  cudaFree(d_out);

  // Deallocate host memory
  free(a); 
  free(b); 
  free(out);
}

cd babel
nvcc gpu_vector_add_dim1_grid1_block256.cu -o gpu_vector_add_dim1_grid1_block256
./gpu_vector_add_dim1_grid1_block256

dim 1, grid 1, block 256 N10000000 with time


#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <assert.h>
#include <cuda.h>
#include <cuda_runtime.h>

#define N 10000000
#define MAX_ERR 1e-6

__global__ void vector_add(float *out, float *a, float *b, int n) {
  int index = threadIdx.x;
  int stride = blockDim.x;

  for(int i = index; i < n; i += stride){
    out[i] = a[i] + b[i];
  }
}

int main(){
  float *a, *b, *out;
  float *d_a, *d_b, *d_out; 

  // Allocate host memory
  a   = (float*)malloc(sizeof(float) * N);
  b   = (float*)malloc(sizeof(float) * N);
  out = (float*)malloc(sizeof(float) * N);

  // Initialize host arrays
  for(int i = 0; i < N; i++){
    a[i] = 1.0f;
    b[i] = 2.0f;
  }

  // Allocate device memory 
  cudaMalloc((void**)&d_a, sizeof(float) * N);
  cudaMalloc((void**)&d_b, sizeof(float) * N);
  cudaMalloc((void**)&d_out, sizeof(float) * N);

  cudaEvent_t start, stop;
  cudaEventCreate(&start);
  cudaEventCreate(&stop);

  cudaEventRecord(start, 0);
  // Transfer data from host to device memory
  cudaMemcpy(d_a, a, sizeof(float) * N, cudaMemcpyHostToDevice);
  cudaMemcpy(d_b, b, sizeof(float) * N, cudaMemcpyHostToDevice);

  // Executing kernel 
  vector_add<<<1,256>>>(d_out, d_a, d_b, N);

  // Transfer data back to host memory
  cudaMemcpy(out, d_out, sizeof(float) * N, cudaMemcpyDeviceToHost);

  cudaEventRecord(stop, 0);
  cudaEventSynchronize(stop);
  float elapsedTime;
  cudaEventElapsedTime(&elapsedTime, start, stop);



  // Verification
  for(int i = 0; i < N; i++){
    assert(fabs(out[i] - a[i] - b[i]) < MAX_ERR);
  }

  printf("PASSED with %f ms\n", elapsedTime);

  cudaEventDestroy(start);
  cudaEventDestroy(stop);


  // Deallocate device memory
  cudaFree(d_a);
  cudaFree(d_b);
  cudaFree(d_out);

  // Deallocate host memory
  free(a); 
  free(b); 
  free(out);
}

cd babel
nvcc gpu_vector_add_dim1_grid1_block256_withtime.cu -o gpu_vector_add_dim1_grid1_block256_withtime
./gpu_vector_add_dim1_grid1_block256_withtime

dim 1, grid N, block 1, (N=256)

#include <stdio.h>
#include <cuda.h>
#include <cuda_runtime.h>
#include <curand_kernel.h>
#define N 512
__global__ void add(int *a, int *b, int *c){
  int tid = blockIdx.x; // handle the data at this index
  if(tid < N)
    c[tid] = a[tid] + b[tid];
}
int main()
{
  int a[N], b[N], c[N], i;
  int *dev_a, *dev_b, *dev_c;
  cudaMalloc((void**)&dev_c, N*sizeof(int));
  cudaMalloc((void**)&dev_b, N*sizeof(int));
  cudaMalloc((void**)&dev_a, N*sizeof(int));
  for(i=0; i < N; i++)
    {
      a[i] = -i;
      b[i] = i*i*i;
    }
  cudaMemcpy(dev_a, a, N*sizeof(int), cudaMemcpyHostToDevice);
  cudaMemcpy(dev_b, b, N*sizeof(int), cudaMemcpyHostToDevice);
  add <<<N, 1>>>(dev_a, dev_b, dev_c);
  cudaMemcpy(c, dev_c, N*sizeof(int), cudaMemcpyDeviceToHost);
  for(i=0; i < N; i++)
    printf("%d + %d = %d\n", a[i], b[i], c[i]);
  cudaFree(dev_c);
  cudaFree(dev_b);
  cudaFree(dev_a);
  return 0;
}
cd babel
nvcc dim1_gridN_block1.cu -o dim1_gridN_block1
./dim1_gridN_block1
0 + 0 = 0
-1 + 1 = 0
-2 + 8 = 6
-3 + 27 = 24
-4 + 64 = 60
-5 + 125 = 120
-6 + 216 = 210
-7 + 343 = 336
-8 + 512 = 504
-9 + 729 = 720
-10 + 1000 = 990
-11 + 1331 = 1320
-12 + 1728 = 1716
-13 + 2197 = 2184
-14 + 2744 = 2730
-15 + 3375 = 3360
-16 + 4096 = 4080
-17 + 4913 = 4896
-18 + 5832 = 5814
-19 + 6859 = 6840
-20 + 8000 = 7980
-21 + 9261 = 9240
-22 + 10648 = 10626
-23 + 12167 = 12144
-24 + 13824 = 13800
-25 + 15625 = 15600
-26 + 17576 = 17550
-27 + 19683 = 19656
-28 + 21952 = 21924
-29 + 24389 = 24360
-30 + 27000 = 26970
-31 + 29791 = 29760
-32 + 32768 = 32736
-33 + 35937 = 35904
-34 + 39304 = 39270
-35 + 42875 = 42840
-36 + 46656 = 46620
-37 + 50653 = 50616
-38 + 54872 = 54834
-39 + 59319 = 59280
-40 + 64000 = 63960
-41 + 68921 = 68880
-42 + 74088 = 74046
-43 + 79507 = 79464
-44 + 85184 = 85140
-45 + 91125 = 91080
-46 + 97336 = 97290
-47 + 103823 = 103776
-48 + 110592 = 110544
-49 + 117649 = 117600
-50 + 125000 = 124950
-51 + 132651 = 132600
-52 + 140608 = 140556
-53 + 148877 = 148824
-54 + 157464 = 157410
-55 + 166375 = 166320
-56 + 175616 = 175560
-57 + 185193 = 185136
-58 + 195112 = 195054
-59 + 205379 = 205320
-60 + 216000 = 215940
-61 + 226981 = 226920
-62 + 238328 = 238266
-63 + 250047 = 249984
-64 + 262144 = 262080
-65 + 274625 = 274560
-66 + 287496 = 287430
-67 + 300763 = 300696
-68 + 314432 = 314364
-69 + 328509 = 328440
-70 + 343000 = 342930
-71 + 357911 = 357840
-72 + 373248 = 373176
-73 + 389017 = 388944
-74 + 405224 = 405150
-75 + 421875 = 421800
-76 + 438976 = 438900
-77 + 456533 = 456456
-78 + 474552 = 474474
-79 + 493039 = 492960
-80 + 512000 = 511920
-81 + 531441 = 531360
-82 + 551368 = 551286
-83 + 571787 = 571704
-84 + 592704 = 592620
-85 + 614125 = 614040
-86 + 636056 = 635970
-87 + 658503 = 658416
-88 + 681472 = 681384
-89 + 704969 = 704880
-90 + 729000 = 728910
-91 + 753571 = 753480
-92 + 778688 = 778596
-93 + 804357 = 804264
-94 + 830584 = 830490
-95 + 857375 = 857280
-96 + 884736 = 884640
-97 + 912673 = 912576
-98 + 941192 = 941094
-99 + 970299 = 970200
-100 + 1000000 = 999900
-101 + 1030301 = 1030200
-102 + 1061208 = 1061106
-103 + 1092727 = 1092624
-104 + 1124864 = 1124760
-105 + 1157625 = 1157520
-106 + 1191016 = 1190910
-107 + 1225043 = 1224936
-108 + 1259712 = 1259604
-109 + 1295029 = 1294920
-110 + 1331000 = 1330890
-111 + 1367631 = 1367520
-112 + 1404928 = 1404816
-113 + 1442897 = 1442784
-114 + 1481544 = 1481430
-115 + 1520875 = 1520760
-116 + 1560896 = 1560780
-117 + 1601613 = 1601496
-118 + 1643032 = 1642914
-119 + 1685159 = 1685040
-120 + 1728000 = 1727880
-121 + 1771561 = 1771440
-122 + 1815848 = 1815726
-123 + 1860867 = 1860744
-124 + 1906624 = 1906500
-125 + 1953125 = 1953000
-126 + 2000376 = 2000250
-127 + 2048383 = 2048256
-128 + 2097152 = 2097024
-129 + 2146689 = 2146560
-130 + 2197000 = 2196870
-131 + 2248091 = 2247960
-132 + 2299968 = 2299836
-133 + 2352637 = 2352504
-134 + 2406104 = 2405970
-135 + 2460375 = 2460240
-136 + 2515456 = 2515320
-137 + 2571353 = 2571216
-138 + 2628072 = 2627934
-139 + 2685619 = 2685480
-140 + 2744000 = 2743860
-141 + 2803221 = 2803080
-142 + 2863288 = 2863146
-143 + 2924207 = 2924064
-144 + 2985984 = 2985840
-145 + 3048625 = 3048480
-146 + 3112136 = 3111990
-147 + 3176523 = 3176376
-148 + 3241792 = 3241644
-149 + 3307949 = 3307800
-150 + 3375000 = 3374850
-151 + 3442951 = 3442800
-152 + 3511808 = 3511656
-153 + 3581577 = 3581424
-154 + 3652264 = 3652110
-155 + 3723875 = 3723720
-156 + 3796416 = 3796260
-157 + 3869893 = 3869736
-158 + 3944312 = 3944154
-159 + 4019679 = 4019520
-160 + 4096000 = 4095840
-161 + 4173281 = 4173120
-162 + 4251528 = 4251366
-163 + 4330747 = 4330584
-164 + 4410944 = 4410780
-165 + 4492125 = 4491960
-166 + 4574296 = 4574130
-167 + 4657463 = 4657296
-168 + 4741632 = 4741464
-169 + 4826809 = 4826640
-170 + 4913000 = 4912830
-171 + 5000211 = 5000040
-172 + 5088448 = 5088276
-173 + 5177717 = 5177544
-174 + 5268024 = 5267850
-175 + 5359375 = 5359200
-176 + 5451776 = 5451600
-177 + 5545233 = 5545056
-178 + 5639752 = 5639574
-179 + 5735339 = 5735160
-180 + 5832000 = 5831820
-181 + 5929741 = 5929560
-182 + 6028568 = 6028386
-183 + 6128487 = 6128304
-184 + 6229504 = 6229320
-185 + 6331625 = 6331440
-186 + 6434856 = 6434670
-187 + 6539203 = 6539016
-188 + 6644672 = 6644484
-189 + 6751269 = 6751080
-190 + 6859000 = 6858810
-191 + 6967871 = 6967680
-192 + 7077888 = 7077696
-193 + 7189057 = 7188864
-194 + 7301384 = 7301190
-195 + 7414875 = 7414680
-196 + 7529536 = 7529340
-197 + 7645373 = 7645176
-198 + 7762392 = 7762194
-199 + 7880599 = 7880400
-200 + 8000000 = 7999800
-201 + 8120601 = 8120400
-202 + 8242408 = 8242206
-203 + 8365427 = 8365224
-204 + 8489664 = 8489460
-205 + 8615125 = 8614920
-206 + 8741816 = 8741610
-207 + 8869743 = 8869536
-208 + 8998912 = 8998704
-209 + 9129329 = 9129120
-210 + 9261000 = 9260790
-211 + 9393931 = 9393720
-212 + 9528128 = 9527916
-213 + 9663597 = 9663384
-214 + 9800344 = 9800130
-215 + 9938375 = 9938160
-216 + 10077696 = 10077480
-217 + 10218313 = 10218096
-218 + 10360232 = 10360014
-219 + 10503459 = 10503240
-220 + 10648000 = 10647780
-221 + 10793861 = 10793640
-222 + 10941048 = 10940826
-223 + 11089567 = 11089344
-224 + 11239424 = 11239200
-225 + 11390625 = 11390400
-226 + 11543176 = 11542950
-227 + 11697083 = 11696856
-228 + 11852352 = 11852124
-229 + 12008989 = 12008760
-230 + 12167000 = 12166770
-231 + 12326391 = 12326160
-232 + 12487168 = 12486936
-233 + 12649337 = 12649104
-234 + 12812904 = 12812670
-235 + 12977875 = 12977640
-236 + 13144256 = 13144020
-237 + 13312053 = 13311816
-238 + 13481272 = 13481034
-239 + 13651919 = 13651680
-240 + 13824000 = 13823760
-241 + 13997521 = 13997280
-242 + 14172488 = 14172246
-243 + 14348907 = 14348664
-244 + 14526784 = 14526540
-245 + 14706125 = 14705880
-246 + 14886936 = 14886690
-247 + 15069223 = 15068976
-248 + 15252992 = 15252744
-249 + 15438249 = 15438000
-250 + 15625000 = 15624750
-251 + 15813251 = 15813000
-252 + 16003008 = 16002756
-253 + 16194277 = 16194024
-254 + 16387064 = 16386810
-255 + 16581375 = 16581120
-256 + 16777216 = 16776960
-257 + 16974593 = 16974336
-258 + 17173512 = 17173254
-259 + 17373979 = 17373720
-260 + 17576000 = 17575740
-261 + 17779581 = 17779320
-262 + 17984728 = 17984466
-263 + 18191447 = 18191184
-264 + 18399744 = 18399480
-265 + 18609625 = 18609360
-266 + 18821096 = 18820830
-267 + 19034163 = 19033896
-268 + 19248832 = 19248564
-269 + 19465109 = 19464840
-270 + 19683000 = 19682730
-271 + 19902511 = 19902240
-272 + 20123648 = 20123376
-273 + 20346417 = 20346144
-274 + 20570824 = 20570550
-275 + 20796875 = 20796600
-276 + 21024576 = 21024300
-277 + 21253933 = 21253656
-278 + 21484952 = 21484674
-279 + 21717639 = 21717360
-280 + 21952000 = 21951720
-281 + 22188041 = 22187760
-282 + 22425768 = 22425486
-283 + 22665187 = 22664904
-284 + 22906304 = 22906020
-285 + 23149125 = 23148840
-286 + 23393656 = 23393370
-287 + 23639903 = 23639616
-288 + 23887872 = 23887584
-289 + 24137569 = 24137280
-290 + 24389000 = 24388710
-291 + 24642171 = 24641880
-292 + 24897088 = 24896796
-293 + 25153757 = 25153464
-294 + 25412184 = 25411890
-295 + 25672375 = 25672080
-296 + 25934336 = 25934040
-297 + 26198073 = 26197776
-298 + 26463592 = 26463294
-299 + 26730899 = 26730600
-300 + 27000000 = 26999700
-301 + 27270901 = 27270600
-302 + 27543608 = 27543306
-303 + 27818127 = 27817824
-304 + 28094464 = 28094160
-305 + 28372625 = 28372320
-306 + 28652616 = 28652310
-307 + 28934443 = 28934136
-308 + 29218112 = 29217804
-309 + 29503629 = 29503320
-310 + 29791000 = 29790690
-311 + 30080231 = 30079920
-312 + 30371328 = 30371016
-313 + 30664297 = 30663984
-314 + 30959144 = 30958830
-315 + 31255875 = 31255560
-316 + 31554496 = 31554180
-317 + 31855013 = 31854696
-318 + 32157432 = 32157114
-319 + 32461759 = 32461440
-320 + 32768000 = 32767680
-321 + 33076161 = 33075840
-322 + 33386248 = 33385926
-323 + 33698267 = 33697944
-324 + 34012224 = 34011900
-325 + 34328125 = 34327800
-326 + 34645976 = 34645650
-327 + 34965783 = 34965456
-328 + 35287552 = 35287224
-329 + 35611289 = 35610960
-330 + 35937000 = 35936670
-331 + 36264691 = 36264360
-332 + 36594368 = 36594036
-333 + 36926037 = 36925704
-334 + 37259704 = 37259370
-335 + 37595375 = 37595040
-336 + 37933056 = 37932720
-337 + 38272753 = 38272416
-338 + 38614472 = 38614134
-339 + 38958219 = 38957880
-340 + 39304000 = 39303660
-341 + 39651821 = 39651480
-342 + 40001688 = 40001346
-343 + 40353607 = 40353264
-344 + 40707584 = 40707240
-345 + 41063625 = 41063280
-346 + 41421736 = 41421390
-347 + 41781923 = 41781576
-348 + 42144192 = 42143844
-349 + 42508549 = 42508200
-350 + 42875000 = 42874650
-351 + 43243551 = 43243200
-352 + 43614208 = 43613856
-353 + 43986977 = 43986624
-354 + 44361864 = 44361510
-355 + 44738875 = 44738520
-356 + 45118016 = 45117660
-357 + 45499293 = 45498936
-358 + 45882712 = 45882354
-359 + 46268279 = 46267920
-360 + 46656000 = 46655640
-361 + 47045881 = 47045520
-362 + 47437928 = 47437566
-363 + 47832147 = 47831784
-364 + 48228544 = 48228180
-365 + 48627125 = 48626760
-366 + 49027896 = 49027530
-367 + 49430863 = 49430496
-368 + 49836032 = 49835664
-369 + 50243409 = 50243040
-370 + 50653000 = 50652630
-371 + 51064811 = 51064440
-372 + 51478848 = 51478476
-373 + 51895117 = 51894744
-374 + 52313624 = 52313250
-375 + 52734375 = 52734000
-376 + 53157376 = 53157000
-377 + 53582633 = 53582256
-378 + 54010152 = 54009774
-379 + 54439939 = 54439560
-380 + 54872000 = 54871620
-381 + 55306341 = 55305960
-382 + 55742968 = 55742586
-383 + 56181887 = 56181504
-384 + 56623104 = 56622720
-385 + 57066625 = 57066240
-386 + 57512456 = 57512070
-387 + 57960603 = 57960216
-388 + 58411072 = 58410684
-389 + 58863869 = 58863480
-390 + 59319000 = 59318610
-391 + 59776471 = 59776080
-392 + 60236288 = 60235896
-393 + 60698457 = 60698064
-394 + 61162984 = 61162590
-395 + 61629875 = 61629480
-396 + 62099136 = 62098740
-397 + 62570773 = 62570376
-398 + 63044792 = 63044394
-399 + 63521199 = 63520800
-400 + 64000000 = 63999600
-401 + 64481201 = 64480800
-402 + 64964808 = 64964406
-403 + 65450827 = 65450424
-404 + 65939264 = 65938860
-405 + 66430125 = 66429720
-406 + 66923416 = 66923010
-407 + 67419143 = 67418736
-408 + 67917312 = 67916904
-409 + 68417929 = 68417520
-410 + 68921000 = 68920590
-411 + 69426531 = 69426120
-412 + 69934528 = 69934116
-413 + 70444997 = 70444584
-414 + 70957944 = 70957530
-415 + 71473375 = 71472960
-416 + 71991296 = 71990880
-417 + 72511713 = 72511296
-418 + 73034632 = 73034214
-419 + 73560059 = 73559640
-420 + 74088000 = 74087580
-421 + 74618461 = 74618040
-422 + 75151448 = 75151026
-423 + 75686967 = 75686544
-424 + 76225024 = 76224600
-425 + 76765625 = 76765200
-426 + 77308776 = 77308350
-427 + 77854483 = 77854056
-428 + 78402752 = 78402324
-429 + 78953589 = 78953160
-430 + 79507000 = 79506570
-431 + 80062991 = 80062560
-432 + 80621568 = 80621136
-433 + 81182737 = 81182304
-434 + 81746504 = 81746070
-435 + 82312875 = 82312440
-436 + 82881856 = 82881420
-437 + 83453453 = 83453016
-438 + 84027672 = 84027234
-439 + 84604519 = 84604080
-440 + 85184000 = 85183560
-441 + 85766121 = 85765680
-442 + 86350888 = 86350446
-443 + 86938307 = 86937864
-444 + 87528384 = 87527940
-445 + 88121125 = 88120680
-446 + 88716536 = 88716090
-447 + 89314623 = 89314176
-448 + 89915392 = 89914944
-449 + 90518849 = 90518400
-450 + 91125000 = 91124550
-451 + 91733851 = 91733400
-452 + 92345408 = 92344956
-453 + 92959677 = 92959224
-454 + 93576664 = 93576210
-455 + 94196375 = 94195920
-456 + 94818816 = 94818360
-457 + 95443993 = 95443536
-458 + 96071912 = 96071454
-459 + 96702579 = 96702120
-460 + 97336000 = 97335540
-461 + 97972181 = 97971720
-462 + 98611128 = 98610666
-463 + 99252847 = 99252384
-464 + 99897344 = 99896880
-465 + 100544625 = 100544160
-466 + 101194696 = 101194230
-467 + 101847563 = 101847096
-468 + 102503232 = 102502764
-469 + 103161709 = 103161240
-470 + 103823000 = 103822530
-471 + 104487111 = 104486640
-472 + 105154048 = 105153576
-473 + 105823817 = 105823344
-474 + 106496424 = 106495950
-475 + 107171875 = 107171400
-476 + 107850176 = 107849700
-477 + 108531333 = 108530856
-478 + 109215352 = 109214874
-479 + 109902239 = 109901760
-480 + 110592000 = 110591520
-481 + 111284641 = 111284160
-482 + 111980168 = 111979686
-483 + 112678587 = 112678104
-484 + 113379904 = 113379420
-485 + 114084125 = 114083640
-486 + 114791256 = 114790770
-487 + 115501303 = 115500816
-488 + 116214272 = 116213784
-489 + 116930169 = 116929680
-490 + 117649000 = 117648510
-491 + 118370771 = 118370280
-492 + 119095488 = 119094996
-493 + 119823157 = 119822664
-494 + 120553784 = 120553290
-495 + 121287375 = 121286880
-496 + 122023936 = 122023440
-497 + 122763473 = 122762976
-498 + 123505992 = 123505494
-499 + 124251499 = 124251000
-500 + 125000000 = 124999500
-501 + 125751501 = 125751000
-502 + 126506008 = 126505506
-503 + 127263527 = 127263024
-504 + 128024064 = 128023560
-505 + 128787625 = 128787120
-506 + 129554216 = 129553710
-507 + 130323843 = 130323336
-508 + 131096512 = 131096004
-509 + 131872229 = 131871720
-510 + 132651000 = 132650490
-511 + 133432831 = 133432320

dim 1, grid 1, block N, (N=256)

#include <stdio.h>
#include <cuda.h>
#include <cuda_runtime.h>
#include <curand_kernel.h>
#define N 512
__global__ void add(int *a, int *b, int *c){
  int tid = threadIdx.x; // handle the data at this index
  if(tid < N)
    c[tid] = a[tid] + b[tid];
}
int main()
{
  int a[N], b[N], c[N], i;
  int *dev_a, *dev_b, *dev_c;
  cudaMalloc((void**)&dev_c, N*sizeof(int));
  cudaMalloc((void**)&dev_b, N*sizeof(int));
  cudaMalloc((void**)&dev_a, N*sizeof(int));
  for(i=0; i < N; i++)
    {
      a[i] = -i;
      b[i] = i*i*i;
    }
  cudaMemcpy(dev_a, a, N*sizeof(int), cudaMemcpyHostToDevice);
  cudaMemcpy(dev_b, b, N*sizeof(int), cudaMemcpyHostToDevice);
  add <<<1, N>>>(dev_a, dev_b, dev_c);
  cudaMemcpy(c, dev_c, N*sizeof(int), cudaMemcpyDeviceToHost);
  for(i=0; i < N; i++)
    printf("%d + %d = %d\n", a[i], b[i], c[i]);
  cudaFree(dev_c);
  cudaFree(dev_b);
  cudaFree(dev_a);
  return 0;
}
cd babel
nvcc dim1_gridN_block1_N256.cu -o dim1_gridN_block1_N256
./dim1_gridN_block1_N256
0 + 0 = 0
-1 + 1 = 0
-2 + 8 = 6
-3 + 27 = 24
-4 + 64 = 60
-5 + 125 = 120
-6 + 216 = 210
-7 + 343 = 336
-8 + 512 = 504
-9 + 729 = 720
-10 + 1000 = 990
-11 + 1331 = 1320
-12 + 1728 = 1716
-13 + 2197 = 2184
-14 + 2744 = 2730
-15 + 3375 = 3360
-16 + 4096 = 4080
-17 + 4913 = 4896
-18 + 5832 = 5814
-19 + 6859 = 6840
-20 + 8000 = 7980
-21 + 9261 = 9240
-22 + 10648 = 10626
-23 + 12167 = 12144
-24 + 13824 = 13800
-25 + 15625 = 15600
-26 + 17576 = 17550
-27 + 19683 = 19656
-28 + 21952 = 21924
-29 + 24389 = 24360
-30 + 27000 = 26970
-31 + 29791 = 29760
-32 + 32768 = 32736
-33 + 35937 = 35904
-34 + 39304 = 39270
-35 + 42875 = 42840
-36 + 46656 = 46620
-37 + 50653 = 50616
-38 + 54872 = 54834
-39 + 59319 = 59280
-40 + 64000 = 63960
-41 + 68921 = 68880
-42 + 74088 = 74046
-43 + 79507 = 79464
-44 + 85184 = 85140
-45 + 91125 = 91080
-46 + 97336 = 97290
-47 + 103823 = 103776
-48 + 110592 = 110544
-49 + 117649 = 117600
-50 + 125000 = 124950
-51 + 132651 = 132600
-52 + 140608 = 140556
-53 + 148877 = 148824
-54 + 157464 = 157410
-55 + 166375 = 166320
-56 + 175616 = 175560
-57 + 185193 = 185136
-58 + 195112 = 195054
-59 + 205379 = 205320
-60 + 216000 = 215940
-61 + 226981 = 226920
-62 + 238328 = 238266
-63 + 250047 = 249984
-64 + 262144 = 262080
-65 + 274625 = 274560
-66 + 287496 = 287430
-67 + 300763 = 300696
-68 + 314432 = 314364
-69 + 328509 = 328440
-70 + 343000 = 342930
-71 + 357911 = 357840
-72 + 373248 = 373176
-73 + 389017 = 388944
-74 + 405224 = 405150
-75 + 421875 = 421800
-76 + 438976 = 438900
-77 + 456533 = 456456
-78 + 474552 = 474474
-79 + 493039 = 492960
-80 + 512000 = 511920
-81 + 531441 = 531360
-82 + 551368 = 551286
-83 + 571787 = 571704
-84 + 592704 = 592620
-85 + 614125 = 614040
-86 + 636056 = 635970
-87 + 658503 = 658416
-88 + 681472 = 681384
-89 + 704969 = 704880
-90 + 729000 = 728910
-91 + 753571 = 753480
-92 + 778688 = 778596
-93 + 804357 = 804264
-94 + 830584 = 830490
-95 + 857375 = 857280
-96 + 884736 = 884640
-97 + 912673 = 912576
-98 + 941192 = 941094
-99 + 970299 = 970200
-100 + 1000000 = 999900
-101 + 1030301 = 1030200
-102 + 1061208 = 1061106
-103 + 1092727 = 1092624
-104 + 1124864 = 1124760
-105 + 1157625 = 1157520
-106 + 1191016 = 1190910
-107 + 1225043 = 1224936
-108 + 1259712 = 1259604
-109 + 1295029 = 1294920
-110 + 1331000 = 1330890
-111 + 1367631 = 1367520
-112 + 1404928 = 1404816
-113 + 1442897 = 1442784
-114 + 1481544 = 1481430
-115 + 1520875 = 1520760
-116 + 1560896 = 1560780
-117 + 1601613 = 1601496
-118 + 1643032 = 1642914
-119 + 1685159 = 1685040
-120 + 1728000 = 1727880
-121 + 1771561 = 1771440
-122 + 1815848 = 1815726
-123 + 1860867 = 1860744
-124 + 1906624 = 1906500
-125 + 1953125 = 1953000
-126 + 2000376 = 2000250
-127 + 2048383 = 2048256
-128 + 2097152 = 2097024
-129 + 2146689 = 2146560
-130 + 2197000 = 2196870
-131 + 2248091 = 2247960
-132 + 2299968 = 2299836
-133 + 2352637 = 2352504
-134 + 2406104 = 2405970
-135 + 2460375 = 2460240
-136 + 2515456 = 2515320
-137 + 2571353 = 2571216
-138 + 2628072 = 2627934
-139 + 2685619 = 2685480
-140 + 2744000 = 2743860
-141 + 2803221 = 2803080
-142 + 2863288 = 2863146
-143 + 2924207 = 2924064
-144 + 2985984 = 2985840
-145 + 3048625 = 3048480
-146 + 3112136 = 3111990
-147 + 3176523 = 3176376
-148 + 3241792 = 3241644
-149 + 3307949 = 3307800
-150 + 3375000 = 3374850
-151 + 3442951 = 3442800
-152 + 3511808 = 3511656
-153 + 3581577 = 3581424
-154 + 3652264 = 3652110
-155 + 3723875 = 3723720
-156 + 3796416 = 3796260
-157 + 3869893 = 3869736
-158 + 3944312 = 3944154
-159 + 4019679 = 4019520
-160 + 4096000 = 4095840
-161 + 4173281 = 4173120
-162 + 4251528 = 4251366
-163 + 4330747 = 4330584
-164 + 4410944 = 4410780
-165 + 4492125 = 4491960
-166 + 4574296 = 4574130
-167 + 4657463 = 4657296
-168 + 4741632 = 4741464
-169 + 4826809 = 4826640
-170 + 4913000 = 4912830
-171 + 5000211 = 5000040
-172 + 5088448 = 5088276
-173 + 5177717 = 5177544
-174 + 5268024 = 5267850
-175 + 5359375 = 5359200
-176 + 5451776 = 5451600
-177 + 5545233 = 5545056
-178 + 5639752 = 5639574
-179 + 5735339 = 5735160
-180 + 5832000 = 5831820
-181 + 5929741 = 5929560
-182 + 6028568 = 6028386
-183 + 6128487 = 6128304
-184 + 6229504 = 6229320
-185 + 6331625 = 6331440
-186 + 6434856 = 6434670
-187 + 6539203 = 6539016
-188 + 6644672 = 6644484
-189 + 6751269 = 6751080
-190 + 6859000 = 6858810
-191 + 6967871 = 6967680
-192 + 7077888 = 7077696
-193 + 7189057 = 7188864
-194 + 7301384 = 7301190
-195 + 7414875 = 7414680
-196 + 7529536 = 7529340
-197 + 7645373 = 7645176
-198 + 7762392 = 7762194
-199 + 7880599 = 7880400
-200 + 8000000 = 7999800
-201 + 8120601 = 8120400
-202 + 8242408 = 8242206
-203 + 8365427 = 8365224
-204 + 8489664 = 8489460
-205 + 8615125 = 8614920
-206 + 8741816 = 8741610
-207 + 8869743 = 8869536
-208 + 8998912 = 8998704
-209 + 9129329 = 9129120
-210 + 9261000 = 9260790
-211 + 9393931 = 9393720
-212 + 9528128 = 9527916
-213 + 9663597 = 9663384
-214 + 9800344 = 9800130
-215 + 9938375 = 9938160
-216 + 10077696 = 10077480
-217 + 10218313 = 10218096
-218 + 10360232 = 10360014
-219 + 10503459 = 10503240
-220 + 10648000 = 10647780
-221 + 10793861 = 10793640
-222 + 10941048 = 10940826
-223 + 11089567 = 11089344
-224 + 11239424 = 11239200
-225 + 11390625 = 11390400
-226 + 11543176 = 11542950
-227 + 11697083 = 11696856
-228 + 11852352 = 11852124
-229 + 12008989 = 12008760
-230 + 12167000 = 12166770
-231 + 12326391 = 12326160
-232 + 12487168 = 12486936
-233 + 12649337 = 12649104
-234 + 12812904 = 12812670
-235 + 12977875 = 12977640
-236 + 13144256 = 13144020
-237 + 13312053 = 13311816
-238 + 13481272 = 13481034
-239 + 13651919 = 13651680
-240 + 13824000 = 13823760
-241 + 13997521 = 13997280
-242 + 14172488 = 14172246
-243 + 14348907 = 14348664
-244 + 14526784 = 14526540
-245 + 14706125 = 14705880
-246 + 14886936 = 14886690
-247 + 15069223 = 15068976
-248 + 15252992 = 15252744
-249 + 15438249 = 15438000
-250 + 15625000 = 15624750
-251 + 15813251 = 15813000
-252 + 16003008 = 16002756
-253 + 16194277 = 16194024
-254 + 16387064 = 16386810
-255 + 16581375 = 16581120
-256 + 16777216 = 16776960
-257 + 16974593 = 16974336
-258 + 17173512 = 17173254
-259 + 17373979 = 17373720
-260 + 17576000 = 17575740
-261 + 17779581 = 17779320
-262 + 17984728 = 17984466
-263 + 18191447 = 18191184
-264 + 18399744 = 18399480
-265 + 18609625 = 18609360
-266 + 18821096 = 18820830
-267 + 19034163 = 19033896
-268 + 19248832 = 19248564
-269 + 19465109 = 19464840
-270 + 19683000 = 19682730
-271 + 19902511 = 19902240
-272 + 20123648 = 20123376
-273 + 20346417 = 20346144
-274 + 20570824 = 20570550
-275 + 20796875 = 20796600
-276 + 21024576 = 21024300
-277 + 21253933 = 21253656
-278 + 21484952 = 21484674
-279 + 21717639 = 21717360
-280 + 21952000 = 21951720
-281 + 22188041 = 22187760
-282 + 22425768 = 22425486
-283 + 22665187 = 22664904
-284 + 22906304 = 22906020
-285 + 23149125 = 23148840
-286 + 23393656 = 23393370
-287 + 23639903 = 23639616
-288 + 23887872 = 23887584
-289 + 24137569 = 24137280
-290 + 24389000 = 24388710
-291 + 24642171 = 24641880
-292 + 24897088 = 24896796
-293 + 25153757 = 25153464
-294 + 25412184 = 25411890
-295 + 25672375 = 25672080
-296 + 25934336 = 25934040
-297 + 26198073 = 26197776
-298 + 26463592 = 26463294
-299 + 26730899 = 26730600
-300 + 27000000 = 26999700
-301 + 27270901 = 27270600
-302 + 27543608 = 27543306
-303 + 27818127 = 27817824
-304 + 28094464 = 28094160
-305 + 28372625 = 28372320
-306 + 28652616 = 28652310
-307 + 28934443 = 28934136
-308 + 29218112 = 29217804
-309 + 29503629 = 29503320
-310 + 29791000 = 29790690
-311 + 30080231 = 30079920
-312 + 30371328 = 30371016
-313 + 30664297 = 30663984
-314 + 30959144 = 30958830
-315 + 31255875 = 31255560
-316 + 31554496 = 31554180
-317 + 31855013 = 31854696
-318 + 32157432 = 32157114
-319 + 32461759 = 32461440
-320 + 32768000 = 32767680
-321 + 33076161 = 33075840
-322 + 33386248 = 33385926
-323 + 33698267 = 33697944
-324 + 34012224 = 34011900
-325 + 34328125 = 34327800
-326 + 34645976 = 34645650
-327 + 34965783 = 34965456
-328 + 35287552 = 35287224
-329 + 35611289 = 35610960
-330 + 35937000 = 35936670
-331 + 36264691 = 36264360
-332 + 36594368 = 36594036
-333 + 36926037 = 36925704
-334 + 37259704 = 37259370
-335 + 37595375 = 37595040
-336 + 37933056 = 37932720
-337 + 38272753 = 38272416
-338 + 38614472 = 38614134
-339 + 38958219 = 38957880
-340 + 39304000 = 39303660
-341 + 39651821 = 39651480
-342 + 40001688 = 40001346
-343 + 40353607 = 40353264
-344 + 40707584 = 40707240
-345 + 41063625 = 41063280
-346 + 41421736 = 41421390
-347 + 41781923 = 41781576
-348 + 42144192 = 42143844
-349 + 42508549 = 42508200
-350 + 42875000 = 42874650
-351 + 43243551 = 43243200
-352 + 43614208 = 43613856
-353 + 43986977 = 43986624
-354 + 44361864 = 44361510
-355 + 44738875 = 44738520
-356 + 45118016 = 45117660
-357 + 45499293 = 45498936
-358 + 45882712 = 45882354
-359 + 46268279 = 46267920
-360 + 46656000 = 46655640
-361 + 47045881 = 47045520
-362 + 47437928 = 47437566
-363 + 47832147 = 47831784
-364 + 48228544 = 48228180
-365 + 48627125 = 48626760
-366 + 49027896 = 49027530
-367 + 49430863 = 49430496
-368 + 49836032 = 49835664
-369 + 50243409 = 50243040
-370 + 50653000 = 50652630
-371 + 51064811 = 51064440
-372 + 51478848 = 51478476
-373 + 51895117 = 51894744
-374 + 52313624 = 52313250
-375 + 52734375 = 52734000
-376 + 53157376 = 53157000
-377 + 53582633 = 53582256
-378 + 54010152 = 54009774
-379 + 54439939 = 54439560
-380 + 54872000 = 54871620
-381 + 55306341 = 55305960
-382 + 55742968 = 55742586
-383 + 56181887 = 56181504
-384 + 56623104 = 56622720
-385 + 57066625 = 57066240
-386 + 57512456 = 57512070
-387 + 57960603 = 57960216
-388 + 58411072 = 58410684
-389 + 58863869 = 58863480
-390 + 59319000 = 59318610
-391 + 59776471 = 59776080
-392 + 60236288 = 60235896
-393 + 60698457 = 60698064
-394 + 61162984 = 61162590
-395 + 61629875 = 61629480
-396 + 62099136 = 62098740
-397 + 62570773 = 62570376
-398 + 63044792 = 63044394
-399 + 63521199 = 63520800
-400 + 64000000 = 63999600
-401 + 64481201 = 64480800
-402 + 64964808 = 64964406
-403 + 65450827 = 65450424
-404 + 65939264 = 65938860
-405 + 66430125 = 66429720
-406 + 66923416 = 66923010
-407 + 67419143 = 67418736
-408 + 67917312 = 67916904
-409 + 68417929 = 68417520
-410 + 68921000 = 68920590
-411 + 69426531 = 69426120
-412 + 69934528 = 69934116
-413 + 70444997 = 70444584
-414 + 70957944 = 70957530
-415 + 71473375 = 71472960
-416 + 71991296 = 71990880
-417 + 72511713 = 72511296
-418 + 73034632 = 73034214
-419 + 73560059 = 73559640
-420 + 74088000 = 74087580
-421 + 74618461 = 74618040
-422 + 75151448 = 75151026
-423 + 75686967 = 75686544
-424 + 76225024 = 76224600
-425 + 76765625 = 76765200
-426 + 77308776 = 77308350
-427 + 77854483 = 77854056
-428 + 78402752 = 78402324
-429 + 78953589 = 78953160
-430 + 79507000 = 79506570
-431 + 80062991 = 80062560
-432 + 80621568 = 80621136
-433 + 81182737 = 81182304
-434 + 81746504 = 81746070
-435 + 82312875 = 82312440
-436 + 82881856 = 82881420
-437 + 83453453 = 83453016
-438 + 84027672 = 84027234
-439 + 84604519 = 84604080
-440 + 85184000 = 85183560
-441 + 85766121 = 85765680
-442 + 86350888 = 86350446
-443 + 86938307 = 86937864
-444 + 87528384 = 87527940
-445 + 88121125 = 88120680
-446 + 88716536 = 88716090
-447 + 89314623 = 89314176
-448 + 89915392 = 89914944
-449 + 90518849 = 90518400
-450 + 91125000 = 91124550
-451 + 91733851 = 91733400
-452 + 92345408 = 92344956
-453 + 92959677 = 92959224
-454 + 93576664 = 93576210
-455 + 94196375 = 94195920
-456 + 94818816 = 94818360
-457 + 95443993 = 95443536
-458 + 96071912 = 96071454
-459 + 96702579 = 96702120
-460 + 97336000 = 97335540
-461 + 97972181 = 97971720
-462 + 98611128 = 98610666
-463 + 99252847 = 99252384
-464 + 99897344 = 99896880
-465 + 100544625 = 100544160
-466 + 101194696 = 101194230
-467 + 101847563 = 101847096
-468 + 102503232 = 102502764
-469 + 103161709 = 103161240
-470 + 103823000 = 103822530
-471 + 104487111 = 104486640
-472 + 105154048 = 105153576
-473 + 105823817 = 105823344
-474 + 106496424 = 106495950
-475 + 107171875 = 107171400
-476 + 107850176 = 107849700
-477 + 108531333 = 108530856
-478 + 109215352 = 109214874
-479 + 109902239 = 109901760
-480 + 110592000 = 110591520
-481 + 111284641 = 111284160
-482 + 111980168 = 111979686
-483 + 112678587 = 112678104
-484 + 113379904 = 113379420
-485 + 114084125 = 114083640
-486 + 114791256 = 114790770
-487 + 115501303 = 115500816
-488 + 116214272 = 116213784
-489 + 116930169 = 116929680
-490 + 117649000 = 117648510
-491 + 118370771 = 118370280
-492 + 119095488 = 119094996
-493 + 119823157 = 119822664
-494 + 120553784 = 120553290
-495 + 121287375 = 121286880
-496 + 122023936 = 122023440
-497 + 122763473 = 122762976
-498 + 123505992 = 123505494
-499 + 124251499 = 124251000
-500 + 125000000 = 124999500
-501 + 125751501 = 125751000
-502 + 126506008 = 126505506
-503 + 127263527 = 127263024
-504 + 128024064 = 128023560
-505 + 128787625 = 128787120
-506 + 129554216 = 129553710
-507 + 130323843 = 130323336
-508 + 131096512 = 131096004
-509 + 131872229 = 131871720
-510 + 132651000 = 132650490
-511 + 133432831 = 133432320

dim 1, grid x, block 256

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <assert.h>
#include <cuda.h>
#include <cuda_runtime.h>

#define N 1000000
#define MAX_ERR 1e-6

__global__ void vector_add(float *out, float *a, float *b, int n) {
  int tid = blockIdx.y * blockDim.x + threadIdx.x;
  int stride = blockDim.x;

  // Handling arbitrary vector size
  for(int i = tid; i < n; i += stride){
    if (i < N){
      out[i] = a[i] + b[i];
    }
  }
}

int main(){
  float *a, *b, *out;
  float *d_a, *d_b, *d_out; 

  // Allocate host memory
  a   = (float*)malloc(sizeof(float) * N);
  b   = (float*)malloc(sizeof(float) * N);
  out = (float*)malloc(sizeof(float) * N);

  // Initialize host arrays
  for(int i = 0; i < N; i++){
    a[i] = 1.0f;
    b[i] = 2.0f;
  }

  // Allocate device memory 
  cudaMalloc((void**)&d_a, sizeof(float) * N);
  cudaMalloc((void**)&d_b, sizeof(float) * N);
  cudaMalloc((void**)&d_out, sizeof(float) * N);

  // Transfer data from host to device memory
  cudaMemcpy(d_a, a, sizeof(float) * N, cudaMemcpyHostToDevice);
  cudaMemcpy(d_b, b, sizeof(float) * N, cudaMemcpyHostToDevice);


  // Executing kernel 
  int block_size = 256;
  int grid_size = ((N + block_size) / block_size);
  vector_add<<<grid_size, block_size>>>(d_out, d_a, d_b, N);

  // Transfer data back to host memory
  cudaMemcpy(out, d_out, sizeof(float) * N, cudaMemcpyDeviceToHost);

  // Verification
  for(int i = 0; i < N; i++){
    assert(fabs(out[i] - a[i] - b[i]) < MAX_ERR);
  }

  printf("PASSED\n");

  // Deallocate device memory
  cudaFree(d_a);
  cudaFree(d_b);
  cudaFree(d_out);

  // Deallocate host memory
  free(a); 
  free(b); 
  free(out);
}
cd babel
nvcc gpu_vector_add_dim1_gridx_block256.cu -o gpu_vector_add_dim1_gridx_block256
./gpu_vector_add_dim1_gridx_block256
PASSED

Addition dim 2 arry in GPU

dim 2, grid 1, block NxN for array

#include <stdio.h>
#include <cuda.h>
#include <assert.h>
#include <cuda_runtime.h>
#include <curand_kernel.h>
#define N 512
__global__ void add(int *a, int *b, int *c){
  int tid = threadIdx.x + threadIdx.y*blockDim.x + blockDim.x*blockDim.y*blockIdx.x; 
  if(tid < N)
    c[tid] = a[tid] + b[tid];
}
int main()
{
  int a[N], b[N], c[N], i;
  int *dev_a, *dev_b, *dev_c;
  cudaMalloc((void**)&dev_c, N*sizeof(int));
  cudaMalloc((void**)&dev_b, N*sizeof(int));
  cudaMalloc((void**)&dev_a, N*sizeof(int));
  for(i=0; i < N; i++)
    {
      a[i] = 1;
      b[i] = 2;
    }
  cudaMemcpy(dev_a, a, N*sizeof(int), cudaMemcpyHostToDevice);
  cudaMemcpy(dev_b, b, N*sizeof(int), cudaMemcpyHostToDevice);
  dim3 BlockPerGrid(1, 1, 1);
  dim3 ThreadsPerBlock(128, 4, 1);
  add <<< BlockPerGrid, ThreadsPerBlock >>>(dev_a, dev_b, dev_c);
  cudaMemcpy(c, dev_c, N*sizeof(int), cudaMemcpyDeviceToHost);
  for(i=0; i < N; i++){
    assert(a[i] + b[i] == c[i]);
  }
  printf("Passed\n");
  cudaFree(dev_c);
  cudaFree(dev_b);
  cudaFree(dev_a);
  return 0;
}



cd babel
nvcc gpu_vector_add_dim2_grid1_blockNxN.cu -o gpu_vector_add_dim2_grid1_blockNxN
./gpu_vector_add_dim2_grid1_blockNxN
Passed

dim 2, grid 1, block NxN for matrix

#include <stdio.h>
#include <cuda.h>
#include <assert.h>
#include <cuda_runtime.h>
#include <curand_kernel.h>
#define n 32
#define N n*n
__global__ void add(float *a, float *b, float *c){
  __shared__ float A[n][n];
  __shared__ float B[n][n];
  __shared__ float C[n][n];
  int tidx = threadIdx.x;
  int tidy = threadIdx.y;

  A[tidy][tidx] = a[tidx +n*tidy];
  B[tidy][tidx] = b[tidx +n*tidy];

  C[tidy][tidx]= A[tidy][tidx] + B[tidy][tidx];

  c[tidx +n*tidy] = C[tidy][tidx];
}
int main()
{
  float a[N], b[N], out[N];
  float *d_a, *d_b, *d_out; 

  for(int i = 0; i < n; i++){
    for (int j = 0; j < n; j++){
      a[i+j*n] = 1.0f + i;
      b[i+j*n] = 1.0f + i;
    }
  }

  // Allocate device memory 
  cudaMalloc((void**)&d_a, sizeof(float) * N);
  cudaMalloc((void**)&d_b, sizeof(float) * N);
  cudaMalloc((void**)&d_out, sizeof(float) * N);

  // Transfer data from host to device memory
  cudaMemcpy(d_a, a, sizeof(float) * N, cudaMemcpyHostToDevice);
  cudaMemcpy(d_b, b, sizeof(float) * N, cudaMemcpyHostToDevice);

  dim3 BlockPerGrid(1, 1, 1);
  dim3 ThreadsPerBlock(n, n, 1);
  add <<< BlockPerGrid, ThreadsPerBlock >>>(d_a, d_b, d_out);
  cudaMemcpy(out, d_out, sizeof(int) * N, cudaMemcpyDeviceToHost);
  for(int i=0; i < N; i++){
    printf("a[%d] + b[%d] == out[%d] is %f + %f = %f\n", i,i,i, a[i], b[i], out[i]);
  }
  printf("Passed\n");
  cudaFree(d_out);
  cudaFree(d_b);
  cudaFree(d_a);
  return 0;
}

cd babel
nvcc gpu_vector_add_dim2_grid1_blockNxN_matrix.cu -o gpu_vector_add_dim2_grid1_blockNxN_matrix
./gpu_vector_add_dim2_grid1_blockNxN_matrix
a[0] + b[0] == out[0] is 1.000000 + 1.000000 = 2.000000
a[1] + b[1] == out[1] is 2.000000 + 2.000000 = 4.000000
a[2] + b[2] == out[2] is 3.000000 + 3.000000 = 6.000000
a[3] + b[3] == out[3] is 4.000000 + 4.000000 = 8.000000
a[4] + b[4] == out[4] is 5.000000 + 5.000000 = 10.000000
a[5] + b[5] == out[5] is 6.000000 + 6.000000 = 12.000000
a[6] + b[6] == out[6] is 7.000000 + 7.000000 = 14.000000
a[7] + b[7] == out[7] is 8.000000 + 8.000000 = 16.000000
a[8] + b[8] == out[8] is 9.000000 + 9.000000 = 18.000000
a[9] + b[9] == out[9] is 10.000000 + 10.000000 = 20.000000
a[10] + b[10] == out[10] is 11.000000 + 11.000000 = 22.000000
a[11] + b[11] == out[11] is 12.000000 + 12.000000 = 24.000000
a[12] + b[12] == out[12] is 13.000000 + 13.000000 = 26.000000
a[13] + b[13] == out[13] is 14.000000 + 14.000000 = 28.000000
a[14] + b[14] == out[14] is 15.000000 + 15.000000 = 30.000000
a[15] + b[15] == out[15] is 16.000000 + 16.000000 = 32.000000
a[16] + b[16] == out[16] is 17.000000 + 17.000000 = 34.000000
a[17] + b[17] == out[17] is 18.000000 + 18.000000 = 36.000000
a[18] + b[18] == out[18] is 19.000000 + 19.000000 = 38.000000
a[19] + b[19] == out[19] is 20.000000 + 20.000000 = 40.000000
a[20] + b[20] == out[20] is 21.000000 + 21.000000 = 42.000000
a[21] + b[21] == out[21] is 22.000000 + 22.000000 = 44.000000
a[22] + b[22] == out[22] is 23.000000 + 23.000000 = 46.000000
a[23] + b[23] == out[23] is 24.000000 + 24.000000 = 48.000000
a[24] + b[24] == out[24] is 25.000000 + 25.000000 = 50.000000
a[25] + b[25] == out[25] is 26.000000 + 26.000000 = 52.000000
a[26] + b[26] == out[26] is 27.000000 + 27.000000 = 54.000000
a[27] + b[27] == out[27] is 28.000000 + 28.000000 = 56.000000
a[28] + b[28] == out[28] is 29.000000 + 29.000000 = 58.000000
a[29] + b[29] == out[29] is 30.000000 + 30.000000 = 60.000000
a[30] + b[30] == out[30] is 31.000000 + 31.000000 = 62.000000
a[31] + b[31] == out[31] is 32.000000 + 32.000000 = 64.000000
a[32] + b[32] == out[32] is 1.000000 + 1.000000 = 2.000000
a[33] + b[33] == out[33] is 2.000000 + 2.000000 = 4.000000
a[34] + b[34] == out[34] is 3.000000 + 3.000000 = 6.000000
a[35] + b[35] == out[35] is 4.000000 + 4.000000 = 8.000000
a[36] + b[36] == out[36] is 5.000000 + 5.000000 = 10.000000
a[37] + b[37] == out[37] is 6.000000 + 6.000000 = 12.000000
a[38] + b[38] == out[38] is 7.000000 + 7.000000 = 14.000000
a[39] + b[39] == out[39] is 8.000000 + 8.000000 = 16.000000
a[40] + b[40] == out[40] is 9.000000 + 9.000000 = 18.000000
a[41] + b[41] == out[41] is 10.000000 + 10.000000 = 20.000000
a[42] + b[42] == out[42] is 11.000000 + 11.000000 = 22.000000
a[43] + b[43] == out[43] is 12.000000 + 12.000000 = 24.000000
a[44] + b[44] == out[44] is 13.000000 + 13.000000 = 26.000000
a[45] + b[45] == out[45] is 14.000000 + 14.000000 = 28.000000
a[46] + b[46] == out[46] is 15.000000 + 15.000000 = 30.000000
a[47] + b[47] == out[47] is 16.000000 + 16.000000 = 32.000000
a[48] + b[48] == out[48] is 17.000000 + 17.000000 = 34.000000
a[49] + b[49] == out[49] is 18.000000 + 18.000000 = 36.000000
a[50] + b[50] == out[50] is 19.000000 + 19.000000 = 38.000000
a[51] + b[51] == out[51] is 20.000000 + 20.000000 = 40.000000
a[52] + b[52] == out[52] is 21.000000 + 21.000000 = 42.000000
a[53] + b[53] == out[53] is 22.000000 + 22.000000 = 44.000000
a[54] + b[54] == out[54] is 23.000000 + 23.000000 = 46.000000
a[55] + b[55] == out[55] is 24.000000 + 24.000000 = 48.000000
a[56] + b[56] == out[56] is 25.000000 + 25.000000 = 50.000000
a[57] + b[57] == out[57] is 26.000000 + 26.000000 = 52.000000
a[58] + b[58] == out[58] is 27.000000 + 27.000000 = 54.000000
a[59] + b[59] == out[59] is 28.000000 + 28.000000 = 56.000000
a[60] + b[60] == out[60] is 29.000000 + 29.000000 = 58.000000
a[61] + b[61] == out[61] is 30.000000 + 30.000000 = 60.000000
a[62] + b[62] == out[62] is 31.000000 + 31.000000 = 62.000000
a[63] + b[63] == out[63] is 32.000000 + 32.000000 = 64.000000
a[64] + b[64] == out[64] is 1.000000 + 1.000000 = 2.000000
a[65] + b[65] == out[65] is 2.000000 + 2.000000 = 4.000000
a[66] + b[66] == out[66] is 3.000000 + 3.000000 = 6.000000
a[67] + b[67] == out[67] is 4.000000 + 4.000000 = 8.000000
a[68] + b[68] == out[68] is 5.000000 + 5.000000 = 10.000000
a[69] + b[69] == out[69] is 6.000000 + 6.000000 = 12.000000
a[70] + b[70] == out[70] is 7.000000 + 7.000000 = 14.000000
a[71] + b[71] == out[71] is 8.000000 + 8.000000 = 16.000000
a[72] + b[72] == out[72] is 9.000000 + 9.000000 = 18.000000
a[73] + b[73] == out[73] is 10.000000 + 10.000000 = 20.000000
a[74] + b[74] == out[74] is 11.000000 + 11.000000 = 22.000000
a[75] + b[75] == out[75] is 12.000000 + 12.000000 = 24.000000
a[76] + b[76] == out[76] is 13.000000 + 13.000000 = 26.000000
a[77] + b[77] == out[77] is 14.000000 + 14.000000 = 28.000000
a[78] + b[78] == out[78] is 15.000000 + 15.000000 = 30.000000
a[79] + b[79] == out[79] is 16.000000 + 16.000000 = 32.000000
a[80] + b[80] == out[80] is 17.000000 + 17.000000 = 34.000000
a[81] + b[81] == out[81] is 18.000000 + 18.000000 = 36.000000
a[82] + b[82] == out[82] is 19.000000 + 19.000000 = 38.000000
a[83] + b[83] == out[83] is 20.000000 + 20.000000 = 40.000000
a[84] + b[84] == out[84] is 21.000000 + 21.000000 = 42.000000
a[85] + b[85] == out[85] is 22.000000 + 22.000000 = 44.000000
a[86] + b[86] == out[86] is 23.000000 + 23.000000 = 46.000000
a[87] + b[87] == out[87] is 24.000000 + 24.000000 = 48.000000
a[88] + b[88] == out[88] is 25.000000 + 25.000000 = 50.000000
a[89] + b[89] == out[89] is 26.000000 + 26.000000 = 52.000000
a[90] + b[90] == out[90] is 27.000000 + 27.000000 = 54.000000
a[91] + b[91] == out[91] is 28.000000 + 28.000000 = 56.000000
a[92] + b[92] == out[92] is 29.000000 + 29.000000 = 58.000000
a[93] + b[93] == out[93] is 30.000000 + 30.000000 = 60.000000
a[94] + b[94] == out[94] is 31.000000 + 31.000000 = 62.000000
a[95] + b[95] == out[95] is 32.000000 + 32.000000 = 64.000000
a[96] + b[96] == out[96] is 1.000000 + 1.000000 = 2.000000
a[97] + b[97] == out[97] is 2.000000 + 2.000000 = 4.000000
a[98] + b[98] == out[98] is 3.000000 + 3.000000 = 6.000000
a[99] + b[99] == out[99] is 4.000000 + 4.000000 = 8.000000
a[100] + b[100] == out[100] is 5.000000 + 5.000000 = 10.000000
a[101] + b[101] == out[101] is 6.000000 + 6.000000 = 12.000000
a[102] + b[102] == out[102] is 7.000000 + 7.000000 = 14.000000
a[103] + b[103] == out[103] is 8.000000 + 8.000000 = 16.000000
a[104] + b[104] == out[104] is 9.000000 + 9.000000 = 18.000000
a[105] + b[105] == out[105] is 10.000000 + 10.000000 = 20.000000
a[106] + b[106] == out[106] is 11.000000 + 11.000000 = 22.000000
a[107] + b[107] == out[107] is 12.000000 + 12.000000 = 24.000000
a[108] + b[108] == out[108] is 13.000000 + 13.000000 = 26.000000
a[109] + b[109] == out[109] is 14.000000 + 14.000000 = 28.000000
a[110] + b[110] == out[110] is 15.000000 + 15.000000 = 30.000000
a[111] + b[111] == out[111] is 16.000000 + 16.000000 = 32.000000
a[112] + b[112] == out[112] is 17.000000 + 17.000000 = 34.000000
a[113] + b[113] == out[113] is 18.000000 + 18.000000 = 36.000000
a[114] + b[114] == out[114] is 19.000000 + 19.000000 = 38.000000
a[115] + b[115] == out[115] is 20.000000 + 20.000000 = 40.000000
a[116] + b[116] == out[116] is 21.000000 + 21.000000 = 42.000000
a[117] + b[117] == out[117] is 22.000000 + 22.000000 = 44.000000
a[118] + b[118] == out[118] is 23.000000 + 23.000000 = 46.000000
a[119] + b[119] == out[119] is 24.000000 + 24.000000 = 48.000000
a[120] + b[120] == out[120] is 25.000000 + 25.000000 = 50.000000
a[121] + b[121] == out[121] is 26.000000 + 26.000000 = 52.000000
a[122] + b[122] == out[122] is 27.000000 + 27.000000 = 54.000000
a[123] + b[123] == out[123] is 28.000000 + 28.000000 = 56.000000
a[124] + b[124] == out[124] is 29.000000 + 29.000000 = 58.000000
a[125] + b[125] == out[125] is 30.000000 + 30.000000 = 60.000000
a[126] + b[126] == out[126] is 31.000000 + 31.000000 = 62.000000
a[127] + b[127] == out[127] is 32.000000 + 32.000000 = 64.000000
a[128] + b[128] == out[128] is 1.000000 + 1.000000 = 2.000000
a[129] + b[129] == out[129] is 2.000000 + 2.000000 = 4.000000
a[130] + b[130] == out[130] is 3.000000 + 3.000000 = 6.000000
a[131] + b[131] == out[131] is 4.000000 + 4.000000 = 8.000000
a[132] + b[132] == out[132] is 5.000000 + 5.000000 = 10.000000
a[133] + b[133] == out[133] is 6.000000 + 6.000000 = 12.000000
a[134] + b[134] == out[134] is 7.000000 + 7.000000 = 14.000000
a[135] + b[135] == out[135] is 8.000000 + 8.000000 = 16.000000
a[136] + b[136] == out[136] is 9.000000 + 9.000000 = 18.000000
a[137] + b[137] == out[137] is 10.000000 + 10.000000 = 20.000000
a[138] + b[138] == out[138] is 11.000000 + 11.000000 = 22.000000
a[139] + b[139] == out[139] is 12.000000 + 12.000000 = 24.000000
a[140] + b[140] == out[140] is 13.000000 + 13.000000 = 26.000000
a[141] + b[141] == out[141] is 14.000000 + 14.000000 = 28.000000
a[142] + b[142] == out[142] is 15.000000 + 15.000000 = 30.000000
a[143] + b[143] == out[143] is 16.000000 + 16.000000 = 32.000000
a[144] + b[144] == out[144] is 17.000000 + 17.000000 = 34.000000
a[145] + b[145] == out[145] is 18.000000 + 18.000000 = 36.000000
a[146] + b[146] == out[146] is 19.000000 + 19.000000 = 38.000000
a[147] + b[147] == out[147] is 20.000000 + 20.000000 = 40.000000
a[148] + b[148] == out[148] is 21.000000 + 21.000000 = 42.000000
a[149] + b[149] == out[149] is 22.000000 + 22.000000 = 44.000000
a[150] + b[150] == out[150] is 23.000000 + 23.000000 = 46.000000
a[151] + b[151] == out[151] is 24.000000 + 24.000000 = 48.000000
a[152] + b[152] == out[152] is 25.000000 + 25.000000 = 50.000000
a[153] + b[153] == out[153] is 26.000000 + 26.000000 = 52.000000
a[154] + b[154] == out[154] is 27.000000 + 27.000000 = 54.000000
a[155] + b[155] == out[155] is 28.000000 + 28.000000 = 56.000000
a[156] + b[156] == out[156] is 29.000000 + 29.000000 = 58.000000
a[157] + b[157] == out[157] is 30.000000 + 30.000000 = 60.000000
a[158] + b[158] == out[158] is 31.000000 + 31.000000 = 62.000000
a[159] + b[159] == out[159] is 32.000000 + 32.000000 = 64.000000
a[160] + b[160] == out[160] is 1.000000 + 1.000000 = 2.000000
a[161] + b[161] == out[161] is 2.000000 + 2.000000 = 4.000000
a[162] + b[162] == out[162] is 3.000000 + 3.000000 = 6.000000
a[163] + b[163] == out[163] is 4.000000 + 4.000000 = 8.000000
a[164] + b[164] == out[164] is 5.000000 + 5.000000 = 10.000000
a[165] + b[165] == out[165] is 6.000000 + 6.000000 = 12.000000
a[166] + b[166] == out[166] is 7.000000 + 7.000000 = 14.000000
a[167] + b[167] == out[167] is 8.000000 + 8.000000 = 16.000000
a[168] + b[168] == out[168] is 9.000000 + 9.000000 = 18.000000
a[169] + b[169] == out[169] is 10.000000 + 10.000000 = 20.000000
a[170] + b[170] == out[170] is 11.000000 + 11.000000 = 22.000000
a[171] + b[171] == out[171] is 12.000000 + 12.000000 = 24.000000
a[172] + b[172] == out[172] is 13.000000 + 13.000000 = 26.000000
a[173] + b[173] == out[173] is 14.000000 + 14.000000 = 28.000000
a[174] + b[174] == out[174] is 15.000000 + 15.000000 = 30.000000
a[175] + b[175] == out[175] is 16.000000 + 16.000000 = 32.000000
a[176] + b[176] == out[176] is 17.000000 + 17.000000 = 34.000000
a[177] + b[177] == out[177] is 18.000000 + 18.000000 = 36.000000
a[178] + b[178] == out[178] is 19.000000 + 19.000000 = 38.000000
a[179] + b[179] == out[179] is 20.000000 + 20.000000 = 40.000000
a[180] + b[180] == out[180] is 21.000000 + 21.000000 = 42.000000
a[181] + b[181] == out[181] is 22.000000 + 22.000000 = 44.000000
a[182] + b[182] == out[182] is 23.000000 + 23.000000 = 46.000000
a[183] + b[183] == out[183] is 24.000000 + 24.000000 = 48.000000
a[184] + b[184] == out[184] is 25.000000 + 25.000000 = 50.000000
a[185] + b[185] == out[185] is 26.000000 + 26.000000 = 52.000000
a[186] + b[186] == out[186] is 27.000000 + 27.000000 = 54.000000
a[187] + b[187] == out[187] is 28.000000 + 28.000000 = 56.000000
a[188] + b[188] == out[188] is 29.000000 + 29.000000 = 58.000000
a[189] + b[189] == out[189] is 30.000000 + 30.000000 = 60.000000
a[190] + b[190] == out[190] is 31.000000 + 31.000000 = 62.000000
a[191] + b[191] == out[191] is 32.000000 + 32.000000 = 64.000000
a[192] + b[192] == out[192] is 1.000000 + 1.000000 = 2.000000
a[193] + b[193] == out[193] is 2.000000 + 2.000000 = 4.000000
a[194] + b[194] == out[194] is 3.000000 + 3.000000 = 6.000000
a[195] + b[195] == out[195] is 4.000000 + 4.000000 = 8.000000
a[196] + b[196] == out[196] is 5.000000 + 5.000000 = 10.000000
a[197] + b[197] == out[197] is 6.000000 + 6.000000 = 12.000000
a[198] + b[198] == out[198] is 7.000000 + 7.000000 = 14.000000
a[199] + b[199] == out[199] is 8.000000 + 8.000000 = 16.000000
a[200] + b[200] == out[200] is 9.000000 + 9.000000 = 18.000000
a[201] + b[201] == out[201] is 10.000000 + 10.000000 = 20.000000
a[202] + b[202] == out[202] is 11.000000 + 11.000000 = 22.000000
a[203] + b[203] == out[203] is 12.000000 + 12.000000 = 24.000000
a[204] + b[204] == out[204] is 13.000000 + 13.000000 = 26.000000
a[205] + b[205] == out[205] is 14.000000 + 14.000000 = 28.000000
a[206] + b[206] == out[206] is 15.000000 + 15.000000 = 30.000000
a[207] + b[207] == out[207] is 16.000000 + 16.000000 = 32.000000
a[208] + b[208] == out[208] is 17.000000 + 17.000000 = 34.000000
a[209] + b[209] == out[209] is 18.000000 + 18.000000 = 36.000000
a[210] + b[210] == out[210] is 19.000000 + 19.000000 = 38.000000
a[211] + b[211] == out[211] is 20.000000 + 20.000000 = 40.000000
a[212] + b[212] == out[212] is 21.000000 + 21.000000 = 42.000000
a[213] + b[213] == out[213] is 22.000000 + 22.000000 = 44.000000
a[214] + b[214] == out[214] is 23.000000 + 23.000000 = 46.000000
a[215] + b[215] == out[215] is 24.000000 + 24.000000 = 48.000000
a[216] + b[216] == out[216] is 25.000000 + 25.000000 = 50.000000
a[217] + b[217] == out[217] is 26.000000 + 26.000000 = 52.000000
a[218] + b[218] == out[218] is 27.000000 + 27.000000 = 54.000000
a[219] + b[219] == out[219] is 28.000000 + 28.000000 = 56.000000
a[220] + b[220] == out[220] is 29.000000 + 29.000000 = 58.000000
a[221] + b[221] == out[221] is 30.000000 + 30.000000 = 60.000000
a[222] + b[222] == out[222] is 31.000000 + 31.000000 = 62.000000
a[223] + b[223] == out[223] is 32.000000 + 32.000000 = 64.000000
a[224] + b[224] == out[224] is 1.000000 + 1.000000 = 2.000000
a[225] + b[225] == out[225] is 2.000000 + 2.000000 = 4.000000
a[226] + b[226] == out[226] is 3.000000 + 3.000000 = 6.000000
a[227] + b[227] == out[227] is 4.000000 + 4.000000 = 8.000000
a[228] + b[228] == out[228] is 5.000000 + 5.000000 = 10.000000
a[229] + b[229] == out[229] is 6.000000 + 6.000000 = 12.000000
a[230] + b[230] == out[230] is 7.000000 + 7.000000 = 14.000000
a[231] + b[231] == out[231] is 8.000000 + 8.000000 = 16.000000
a[232] + b[232] == out[232] is 9.000000 + 9.000000 = 18.000000
a[233] + b[233] == out[233] is 10.000000 + 10.000000 = 20.000000
a[234] + b[234] == out[234] is 11.000000 + 11.000000 = 22.000000
a[235] + b[235] == out[235] is 12.000000 + 12.000000 = 24.000000
a[236] + b[236] == out[236] is 13.000000 + 13.000000 = 26.000000
a[237] + b[237] == out[237] is 14.000000 + 14.000000 = 28.000000
a[238] + b[238] == out[238] is 15.000000 + 15.000000 = 30.000000
a[239] + b[239] == out[239] is 16.000000 + 16.000000 = 32.000000
a[240] + b[240] == out[240] is 17.000000 + 17.000000 = 34.000000
a[241] + b[241] == out[241] is 18.000000 + 18.000000 = 36.000000
a[242] + b[242] == out[242] is 19.000000 + 19.000000 = 38.000000
a[243] + b[243] == out[243] is 20.000000 + 20.000000 = 40.000000
a[244] + b[244] == out[244] is 21.000000 + 21.000000 = 42.000000
a[245] + b[245] == out[245] is 22.000000 + 22.000000 = 44.000000
a[246] + b[246] == out[246] is 23.000000 + 23.000000 = 46.000000
a[247] + b[247] == out[247] is 24.000000 + 24.000000 = 48.000000
a[248] + b[248] == out[248] is 25.000000 + 25.000000 = 50.000000
a[249] + b[249] == out[249] is 26.000000 + 26.000000 = 52.000000
a[250] + b[250] == out[250] is 27.000000 + 27.000000 = 54.000000
a[251] + b[251] == out[251] is 28.000000 + 28.000000 = 56.000000
a[252] + b[252] == out[252] is 29.000000 + 29.000000 = 58.000000
a[253] + b[253] == out[253] is 30.000000 + 30.000000 = 60.000000
a[254] + b[254] == out[254] is 31.000000 + 31.000000 = 62.000000
a[255] + b[255] == out[255] is 32.000000 + 32.000000 = 64.000000
a[256] + b[256] == out[256] is 1.000000 + 1.000000 = 2.000000
a[257] + b[257] == out[257] is 2.000000 + 2.000000 = 4.000000
a[258] + b[258] == out[258] is 3.000000 + 3.000000 = 6.000000
a[259] + b[259] == out[259] is 4.000000 + 4.000000 = 8.000000
a[260] + b[260] == out[260] is 5.000000 + 5.000000 = 10.000000
a[261] + b[261] == out[261] is 6.000000 + 6.000000 = 12.000000
a[262] + b[262] == out[262] is 7.000000 + 7.000000 = 14.000000
a[263] + b[263] == out[263] is 8.000000 + 8.000000 = 16.000000
a[264] + b[264] == out[264] is 9.000000 + 9.000000 = 18.000000
a[265] + b[265] == out[265] is 10.000000 + 10.000000 = 20.000000
a[266] + b[266] == out[266] is 11.000000 + 11.000000 = 22.000000
a[267] + b[267] == out[267] is 12.000000 + 12.000000 = 24.000000
a[268] + b[268] == out[268] is 13.000000 + 13.000000 = 26.000000
a[269] + b[269] == out[269] is 14.000000 + 14.000000 = 28.000000
a[270] + b[270] == out[270] is 15.000000 + 15.000000 = 30.000000
a[271] + b[271] == out[271] is 16.000000 + 16.000000 = 32.000000
a[272] + b[272] == out[272] is 17.000000 + 17.000000 = 34.000000
a[273] + b[273] == out[273] is 18.000000 + 18.000000 = 36.000000
a[274] + b[274] == out[274] is 19.000000 + 19.000000 = 38.000000
a[275] + b[275] == out[275] is 20.000000 + 20.000000 = 40.000000
a[276] + b[276] == out[276] is 21.000000 + 21.000000 = 42.000000
a[277] + b[277] == out[277] is 22.000000 + 22.000000 = 44.000000
a[278] + b[278] == out[278] is 23.000000 + 23.000000 = 46.000000
a[279] + b[279] == out[279] is 24.000000 + 24.000000 = 48.000000
a[280] + b[280] == out[280] is 25.000000 + 25.000000 = 50.000000
a[281] + b[281] == out[281] is 26.000000 + 26.000000 = 52.000000
a[282] + b[282] == out[282] is 27.000000 + 27.000000 = 54.000000
a[283] + b[283] == out[283] is 28.000000 + 28.000000 = 56.000000
a[284] + b[284] == out[284] is 29.000000 + 29.000000 = 58.000000
a[285] + b[285] == out[285] is 30.000000 + 30.000000 = 60.000000
a[286] + b[286] == out[286] is 31.000000 + 31.000000 = 62.000000
a[287] + b[287] == out[287] is 32.000000 + 32.000000 = 64.000000
a[288] + b[288] == out[288] is 1.000000 + 1.000000 = 2.000000
a[289] + b[289] == out[289] is 2.000000 + 2.000000 = 4.000000
a[290] + b[290] == out[290] is 3.000000 + 3.000000 = 6.000000
a[291] + b[291] == out[291] is 4.000000 + 4.000000 = 8.000000
a[292] + b[292] == out[292] is 5.000000 + 5.000000 = 10.000000
a[293] + b[293] == out[293] is 6.000000 + 6.000000 = 12.000000
a[294] + b[294] == out[294] is 7.000000 + 7.000000 = 14.000000
a[295] + b[295] == out[295] is 8.000000 + 8.000000 = 16.000000
a[296] + b[296] == out[296] is 9.000000 + 9.000000 = 18.000000
a[297] + b[297] == out[297] is 10.000000 + 10.000000 = 20.000000
a[298] + b[298] == out[298] is 11.000000 + 11.000000 = 22.000000
a[299] + b[299] == out[299] is 12.000000 + 12.000000 = 24.000000
a[300] + b[300] == out[300] is 13.000000 + 13.000000 = 26.000000
a[301] + b[301] == out[301] is 14.000000 + 14.000000 = 28.000000
a[302] + b[302] == out[302] is 15.000000 + 15.000000 = 30.000000
a[303] + b[303] == out[303] is 16.000000 + 16.000000 = 32.000000
a[304] + b[304] == out[304] is 17.000000 + 17.000000 = 34.000000
a[305] + b[305] == out[305] is 18.000000 + 18.000000 = 36.000000
a[306] + b[306] == out[306] is 19.000000 + 19.000000 = 38.000000
a[307] + b[307] == out[307] is 20.000000 + 20.000000 = 40.000000
a[308] + b[308] == out[308] is 21.000000 + 21.000000 = 42.000000
a[309] + b[309] == out[309] is 22.000000 + 22.000000 = 44.000000
a[310] + b[310] == out[310] is 23.000000 + 23.000000 = 46.000000
a[311] + b[311] == out[311] is 24.000000 + 24.000000 = 48.000000
a[312] + b[312] == out[312] is 25.000000 + 25.000000 = 50.000000
a[313] + b[313] == out[313] is 26.000000 + 26.000000 = 52.000000
a[314] + b[314] == out[314] is 27.000000 + 27.000000 = 54.000000
a[315] + b[315] == out[315] is 28.000000 + 28.000000 = 56.000000
a[316] + b[316] == out[316] is 29.000000 + 29.000000 = 58.000000
a[317] + b[317] == out[317] is 30.000000 + 30.000000 = 60.000000
a[318] + b[318] == out[318] is 31.000000 + 31.000000 = 62.000000
a[319] + b[319] == out[319] is 32.000000 + 32.000000 = 64.000000
a[320] + b[320] == out[320] is 1.000000 + 1.000000 = 2.000000
a[321] + b[321] == out[321] is 2.000000 + 2.000000 = 4.000000
a[322] + b[322] == out[322] is 3.000000 + 3.000000 = 6.000000
a[323] + b[323] == out[323] is 4.000000 + 4.000000 = 8.000000
a[324] + b[324] == out[324] is 5.000000 + 5.000000 = 10.000000
a[325] + b[325] == out[325] is 6.000000 + 6.000000 = 12.000000
a[326] + b[326] == out[326] is 7.000000 + 7.000000 = 14.000000
a[327] + b[327] == out[327] is 8.000000 + 8.000000 = 16.000000
a[328] + b[328] == out[328] is 9.000000 + 9.000000 = 18.000000
a[329] + b[329] == out[329] is 10.000000 + 10.000000 = 20.000000
a[330] + b[330] == out[330] is 11.000000 + 11.000000 = 22.000000
a[331] + b[331] == out[331] is 12.000000 + 12.000000 = 24.000000
a[332] + b[332] == out[332] is 13.000000 + 13.000000 = 26.000000
a[333] + b[333] == out[333] is 14.000000 + 14.000000 = 28.000000
a[334] + b[334] == out[334] is 15.000000 + 15.000000 = 30.000000
a[335] + b[335] == out[335] is 16.000000 + 16.000000 = 32.000000
a[336] + b[336] == out[336] is 17.000000 + 17.000000 = 34.000000
a[337] + b[337] == out[337] is 18.000000 + 18.000000 = 36.000000
a[338] + b[338] == out[338] is 19.000000 + 19.000000 = 38.000000
a[339] + b[339] == out[339] is 20.000000 + 20.000000 = 40.000000
a[340] + b[340] == out[340] is 21.000000 + 21.000000 = 42.000000
a[341] + b[341] == out[341] is 22.000000 + 22.000000 = 44.000000
a[342] + b[342] == out[342] is 23.000000 + 23.000000 = 46.000000
a[343] + b[343] == out[343] is 24.000000 + 24.000000 = 48.000000
a[344] + b[344] == out[344] is 25.000000 + 25.000000 = 50.000000
a[345] + b[345] == out[345] is 26.000000 + 26.000000 = 52.000000
a[346] + b[346] == out[346] is 27.000000 + 27.000000 = 54.000000
a[347] + b[347] == out[347] is 28.000000 + 28.000000 = 56.000000
a[348] + b[348] == out[348] is 29.000000 + 29.000000 = 58.000000
a[349] + b[349] == out[349] is 30.000000 + 30.000000 = 60.000000
a[350] + b[350] == out[350] is 31.000000 + 31.000000 = 62.000000
a[351] + b[351] == out[351] is 32.000000 + 32.000000 = 64.000000
a[352] + b[352] == out[352] is 1.000000 + 1.000000 = 2.000000
a[353] + b[353] == out[353] is 2.000000 + 2.000000 = 4.000000
a[354] + b[354] == out[354] is 3.000000 + 3.000000 = 6.000000
a[355] + b[355] == out[355] is 4.000000 + 4.000000 = 8.000000
a[356] + b[356] == out[356] is 5.000000 + 5.000000 = 10.000000
a[357] + b[357] == out[357] is 6.000000 + 6.000000 = 12.000000
a[358] + b[358] == out[358] is 7.000000 + 7.000000 = 14.000000
a[359] + b[359] == out[359] is 8.000000 + 8.000000 = 16.000000
a[360] + b[360] == out[360] is 9.000000 + 9.000000 = 18.000000
a[361] + b[361] == out[361] is 10.000000 + 10.000000 = 20.000000
a[362] + b[362] == out[362] is 11.000000 + 11.000000 = 22.000000
a[363] + b[363] == out[363] is 12.000000 + 12.000000 = 24.000000
a[364] + b[364] == out[364] is 13.000000 + 13.000000 = 26.000000
a[365] + b[365] == out[365] is 14.000000 + 14.000000 = 28.000000
a[366] + b[366] == out[366] is 15.000000 + 15.000000 = 30.000000
a[367] + b[367] == out[367] is 16.000000 + 16.000000 = 32.000000
a[368] + b[368] == out[368] is 17.000000 + 17.000000 = 34.000000
a[369] + b[369] == out[369] is 18.000000 + 18.000000 = 36.000000
a[370] + b[370] == out[370] is 19.000000 + 19.000000 = 38.000000
a[371] + b[371] == out[371] is 20.000000 + 20.000000 = 40.000000
a[372] + b[372] == out[372] is 21.000000 + 21.000000 = 42.000000
a[373] + b[373] == out[373] is 22.000000 + 22.000000 = 44.000000
a[374] + b[374] == out[374] is 23.000000 + 23.000000 = 46.000000
a[375] + b[375] == out[375] is 24.000000 + 24.000000 = 48.000000
a[376] + b[376] == out[376] is 25.000000 + 25.000000 = 50.000000
a[377] + b[377] == out[377] is 26.000000 + 26.000000 = 52.000000
a[378] + b[378] == out[378] is 27.000000 + 27.000000 = 54.000000
a[379] + b[379] == out[379] is 28.000000 + 28.000000 = 56.000000
a[380] + b[380] == out[380] is 29.000000 + 29.000000 = 58.000000
a[381] + b[381] == out[381] is 30.000000 + 30.000000 = 60.000000
a[382] + b[382] == out[382] is 31.000000 + 31.000000 = 62.000000
a[383] + b[383] == out[383] is 32.000000 + 32.000000 = 64.000000
a[384] + b[384] == out[384] is 1.000000 + 1.000000 = 2.000000
a[385] + b[385] == out[385] is 2.000000 + 2.000000 = 4.000000
a[386] + b[386] == out[386] is 3.000000 + 3.000000 = 6.000000
a[387] + b[387] == out[387] is 4.000000 + 4.000000 = 8.000000
a[388] + b[388] == out[388] is 5.000000 + 5.000000 = 10.000000
a[389] + b[389] == out[389] is 6.000000 + 6.000000 = 12.000000
a[390] + b[390] == out[390] is 7.000000 + 7.000000 = 14.000000
a[391] + b[391] == out[391] is 8.000000 + 8.000000 = 16.000000
a[392] + b[392] == out[392] is 9.000000 + 9.000000 = 18.000000
a[393] + b[393] == out[393] is 10.000000 + 10.000000 = 20.000000
a[394] + b[394] == out[394] is 11.000000 + 11.000000 = 22.000000
a[395] + b[395] == out[395] is 12.000000 + 12.000000 = 24.000000
a[396] + b[396] == out[396] is 13.000000 + 13.000000 = 26.000000
a[397] + b[397] == out[397] is 14.000000 + 14.000000 = 28.000000
a[398] + b[398] == out[398] is 15.000000 + 15.000000 = 30.000000
a[399] + b[399] == out[399] is 16.000000 + 16.000000 = 32.000000
a[400] + b[400] == out[400] is 17.000000 + 17.000000 = 34.000000
a[401] + b[401] == out[401] is 18.000000 + 18.000000 = 36.000000
a[402] + b[402] == out[402] is 19.000000 + 19.000000 = 38.000000
a[403] + b[403] == out[403] is 20.000000 + 20.000000 = 40.000000
a[404] + b[404] == out[404] is 21.000000 + 21.000000 = 42.000000
a[405] + b[405] == out[405] is 22.000000 + 22.000000 = 44.000000
a[406] + b[406] == out[406] is 23.000000 + 23.000000 = 46.000000
a[407] + b[407] == out[407] is 24.000000 + 24.000000 = 48.000000
a[408] + b[408] == out[408] is 25.000000 + 25.000000 = 50.000000
a[409] + b[409] == out[409] is 26.000000 + 26.000000 = 52.000000
a[410] + b[410] == out[410] is 27.000000 + 27.000000 = 54.000000
a[411] + b[411] == out[411] is 28.000000 + 28.000000 = 56.000000
a[412] + b[412] == out[412] is 29.000000 + 29.000000 = 58.000000
a[413] + b[413] == out[413] is 30.000000 + 30.000000 = 60.000000
a[414] + b[414] == out[414] is 31.000000 + 31.000000 = 62.000000
a[415] + b[415] == out[415] is 32.000000 + 32.000000 = 64.000000
a[416] + b[416] == out[416] is 1.000000 + 1.000000 = 2.000000
a[417] + b[417] == out[417] is 2.000000 + 2.000000 = 4.000000
a[418] + b[418] == out[418] is 3.000000 + 3.000000 = 6.000000
a[419] + b[419] == out[419] is 4.000000 + 4.000000 = 8.000000
a[420] + b[420] == out[420] is 5.000000 + 5.000000 = 10.000000
a[421] + b[421] == out[421] is 6.000000 + 6.000000 = 12.000000
a[422] + b[422] == out[422] is 7.000000 + 7.000000 = 14.000000
a[423] + b[423] == out[423] is 8.000000 + 8.000000 = 16.000000
a[424] + b[424] == out[424] is 9.000000 + 9.000000 = 18.000000
a[425] + b[425] == out[425] is 10.000000 + 10.000000 = 20.000000
a[426] + b[426] == out[426] is 11.000000 + 11.000000 = 22.000000
a[427] + b[427] == out[427] is 12.000000 + 12.000000 = 24.000000
a[428] + b[428] == out[428] is 13.000000 + 13.000000 = 26.000000
a[429] + b[429] == out[429] is 14.000000 + 14.000000 = 28.000000
a[430] + b[430] == out[430] is 15.000000 + 15.000000 = 30.000000
a[431] + b[431] == out[431] is 16.000000 + 16.000000 = 32.000000
a[432] + b[432] == out[432] is 17.000000 + 17.000000 = 34.000000
a[433] + b[433] == out[433] is 18.000000 + 18.000000 = 36.000000
a[434] + b[434] == out[434] is 19.000000 + 19.000000 = 38.000000
a[435] + b[435] == out[435] is 20.000000 + 20.000000 = 40.000000
a[436] + b[436] == out[436] is 21.000000 + 21.000000 = 42.000000
a[437] + b[437] == out[437] is 22.000000 + 22.000000 = 44.000000
a[438] + b[438] == out[438] is 23.000000 + 23.000000 = 46.000000
a[439] + b[439] == out[439] is 24.000000 + 24.000000 = 48.000000
a[440] + b[440] == out[440] is 25.000000 + 25.000000 = 50.000000
a[441] + b[441] == out[441] is 26.000000 + 26.000000 = 52.000000
a[442] + b[442] == out[442] is 27.000000 + 27.000000 = 54.000000
a[443] + b[443] == out[443] is 28.000000 + 28.000000 = 56.000000
a[444] + b[444] == out[444] is 29.000000 + 29.000000 = 58.000000
a[445] + b[445] == out[445] is 30.000000 + 30.000000 = 60.000000
a[446] + b[446] == out[446] is 31.000000 + 31.000000 = 62.000000
a[447] + b[447] == out[447] is 32.000000 + 32.000000 = 64.000000
a[448] + b[448] == out[448] is 1.000000 + 1.000000 = 2.000000
a[449] + b[449] == out[449] is 2.000000 + 2.000000 = 4.000000
a[450] + b[450] == out[450] is 3.000000 + 3.000000 = 6.000000
a[451] + b[451] == out[451] is 4.000000 + 4.000000 = 8.000000
a[452] + b[452] == out[452] is 5.000000 + 5.000000 = 10.000000
a[453] + b[453] == out[453] is 6.000000 + 6.000000 = 12.000000
a[454] + b[454] == out[454] is 7.000000 + 7.000000 = 14.000000
a[455] + b[455] == out[455] is 8.000000 + 8.000000 = 16.000000
a[456] + b[456] == out[456] is 9.000000 + 9.000000 = 18.000000
a[457] + b[457] == out[457] is 10.000000 + 10.000000 = 20.000000
a[458] + b[458] == out[458] is 11.000000 + 11.000000 = 22.000000
a[459] + b[459] == out[459] is 12.000000 + 12.000000 = 24.000000
a[460] + b[460] == out[460] is 13.000000 + 13.000000 = 26.000000
a[461] + b[461] == out[461] is 14.000000 + 14.000000 = 28.000000
a[462] + b[462] == out[462] is 15.000000 + 15.000000 = 30.000000
a[463] + b[463] == out[463] is 16.000000 + 16.000000 = 32.000000
a[464] + b[464] == out[464] is 17.000000 + 17.000000 = 34.000000
a[465] + b[465] == out[465] is 18.000000 + 18.000000 = 36.000000
a[466] + b[466] == out[466] is 19.000000 + 19.000000 = 38.000000
a[467] + b[467] == out[467] is 20.000000 + 20.000000 = 40.000000
a[468] + b[468] == out[468] is 21.000000 + 21.000000 = 42.000000
a[469] + b[469] == out[469] is 22.000000 + 22.000000 = 44.000000
a[470] + b[470] == out[470] is 23.000000 + 23.000000 = 46.000000
a[471] + b[471] == out[471] is 24.000000 + 24.000000 = 48.000000
a[472] + b[472] == out[472] is 25.000000 + 25.000000 = 50.000000
a[473] + b[473] == out[473] is 26.000000 + 26.000000 = 52.000000
a[474] + b[474] == out[474] is 27.000000 + 27.000000 = 54.000000
a[475] + b[475] == out[475] is 28.000000 + 28.000000 = 56.000000
a[476] + b[476] == out[476] is 29.000000 + 29.000000 = 58.000000
a[477] + b[477] == out[477] is 30.000000 + 30.000000 = 60.000000
a[478] + b[478] == out[478] is 31.000000 + 31.000000 = 62.000000
a[479] + b[479] == out[479] is 32.000000 + 32.000000 = 64.000000
a[480] + b[480] == out[480] is 1.000000 + 1.000000 = 2.000000
a[481] + b[481] == out[481] is 2.000000 + 2.000000 = 4.000000
a[482] + b[482] == out[482] is 3.000000 + 3.000000 = 6.000000
a[483] + b[483] == out[483] is 4.000000 + 4.000000 = 8.000000
a[484] + b[484] == out[484] is 5.000000 + 5.000000 = 10.000000
a[485] + b[485] == out[485] is 6.000000 + 6.000000 = 12.000000
a[486] + b[486] == out[486] is 7.000000 + 7.000000 = 14.000000
a[487] + b[487] == out[487] is 8.000000 + 8.000000 = 16.000000
a[488] + b[488] == out[488] is 9.000000 + 9.000000 = 18.000000
a[489] + b[489] == out[489] is 10.000000 + 10.000000 = 20.000000
a[490] + b[490] == out[490] is 11.000000 + 11.000000 = 22.000000
a[491] + b[491] == out[491] is 12.000000 + 12.000000 = 24.000000
a[492] + b[492] == out[492] is 13.000000 + 13.000000 = 26.000000
a[493] + b[493] == out[493] is 14.000000 + 14.000000 = 28.000000
a[494] + b[494] == out[494] is 15.000000 + 15.000000 = 30.000000
a[495] + b[495] == out[495] is 16.000000 + 16.000000 = 32.000000
a[496] + b[496] == out[496] is 17.000000 + 17.000000 = 34.000000
a[497] + b[497] == out[497] is 18.000000 + 18.000000 = 36.000000
a[498] + b[498] == out[498] is 19.000000 + 19.000000 = 38.000000
a[499] + b[499] == out[499] is 20.000000 + 20.000000 = 40.000000
a[500] + b[500] == out[500] is 21.000000 + 21.000000 = 42.000000
a[501] + b[501] == out[501] is 22.000000 + 22.000000 = 44.000000
a[502] + b[502] == out[502] is 23.000000 + 23.000000 = 46.000000
a[503] + b[503] == out[503] is 24.000000 + 24.000000 = 48.000000
a[504] + b[504] == out[504] is 25.000000 + 25.000000 = 50.000000
a[505] + b[505] == out[505] is 26.000000 + 26.000000 = 52.000000
a[506] + b[506] == out[506] is 27.000000 + 27.000000 = 54.000000
a[507] + b[507] == out[507] is 28.000000 + 28.000000 = 56.000000
a[508] + b[508] == out[508] is 29.000000 + 29.000000 = 58.000000
a[509] + b[509] == out[509] is 30.000000 + 30.000000 = 60.000000
a[510] + b[510] == out[510] is 31.000000 + 31.000000 = 62.000000
a[511] + b[511] == out[511] is 32.000000 + 32.000000 = 64.000000
a[512] + b[512] == out[512] is 1.000000 + 1.000000 = 2.000000
a[513] + b[513] == out[513] is 2.000000 + 2.000000 = 4.000000
a[514] + b[514] == out[514] is 3.000000 + 3.000000 = 6.000000
a[515] + b[515] == out[515] is 4.000000 + 4.000000 = 8.000000
a[516] + b[516] == out[516] is 5.000000 + 5.000000 = 10.000000
a[517] + b[517] == out[517] is 6.000000 + 6.000000 = 12.000000
a[518] + b[518] == out[518] is 7.000000 + 7.000000 = 14.000000
a[519] + b[519] == out[519] is 8.000000 + 8.000000 = 16.000000
a[520] + b[520] == out[520] is 9.000000 + 9.000000 = 18.000000
a[521] + b[521] == out[521] is 10.000000 + 10.000000 = 20.000000
a[522] + b[522] == out[522] is 11.000000 + 11.000000 = 22.000000
a[523] + b[523] == out[523] is 12.000000 + 12.000000 = 24.000000
a[524] + b[524] == out[524] is 13.000000 + 13.000000 = 26.000000
a[525] + b[525] == out[525] is 14.000000 + 14.000000 = 28.000000
a[526] + b[526] == out[526] is 15.000000 + 15.000000 = 30.000000
a[527] + b[527] == out[527] is 16.000000 + 16.000000 = 32.000000
a[528] + b[528] == out[528] is 17.000000 + 17.000000 = 34.000000
a[529] + b[529] == out[529] is 18.000000 + 18.000000 = 36.000000
a[530] + b[530] == out[530] is 19.000000 + 19.000000 = 38.000000
a[531] + b[531] == out[531] is 20.000000 + 20.000000 = 40.000000
a[532] + b[532] == out[532] is 21.000000 + 21.000000 = 42.000000
a[533] + b[533] == out[533] is 22.000000 + 22.000000 = 44.000000
a[534] + b[534] == out[534] is 23.000000 + 23.000000 = 46.000000
a[535] + b[535] == out[535] is 24.000000 + 24.000000 = 48.000000
a[536] + b[536] == out[536] is 25.000000 + 25.000000 = 50.000000
a[537] + b[537] == out[537] is 26.000000 + 26.000000 = 52.000000
a[538] + b[538] == out[538] is 27.000000 + 27.000000 = 54.000000
a[539] + b[539] == out[539] is 28.000000 + 28.000000 = 56.000000
a[540] + b[540] == out[540] is 29.000000 + 29.000000 = 58.000000
a[541] + b[541] == out[541] is 30.000000 + 30.000000 = 60.000000
a[542] + b[542] == out[542] is 31.000000 + 31.000000 = 62.000000
a[543] + b[543] == out[543] is 32.000000 + 32.000000 = 64.000000
a[544] + b[544] == out[544] is 1.000000 + 1.000000 = 2.000000
a[545] + b[545] == out[545] is 2.000000 + 2.000000 = 4.000000
a[546] + b[546] == out[546] is 3.000000 + 3.000000 = 6.000000
a[547] + b[547] == out[547] is 4.000000 + 4.000000 = 8.000000
a[548] + b[548] == out[548] is 5.000000 + 5.000000 = 10.000000
a[549] + b[549] == out[549] is 6.000000 + 6.000000 = 12.000000
a[550] + b[550] == out[550] is 7.000000 + 7.000000 = 14.000000
a[551] + b[551] == out[551] is 8.000000 + 8.000000 = 16.000000
a[552] + b[552] == out[552] is 9.000000 + 9.000000 = 18.000000
a[553] + b[553] == out[553] is 10.000000 + 10.000000 = 20.000000
a[554] + b[554] == out[554] is 11.000000 + 11.000000 = 22.000000
a[555] + b[555] == out[555] is 12.000000 + 12.000000 = 24.000000
a[556] + b[556] == out[556] is 13.000000 + 13.000000 = 26.000000
a[557] + b[557] == out[557] is 14.000000 + 14.000000 = 28.000000
a[558] + b[558] == out[558] is 15.000000 + 15.000000 = 30.000000
a[559] + b[559] == out[559] is 16.000000 + 16.000000 = 32.000000
a[560] + b[560] == out[560] is 17.000000 + 17.000000 = 34.000000
a[561] + b[561] == out[561] is 18.000000 + 18.000000 = 36.000000
a[562] + b[562] == out[562] is 19.000000 + 19.000000 = 38.000000
a[563] + b[563] == out[563] is 20.000000 + 20.000000 = 40.000000
a[564] + b[564] == out[564] is 21.000000 + 21.000000 = 42.000000
a[565] + b[565] == out[565] is 22.000000 + 22.000000 = 44.000000
a[566] + b[566] == out[566] is 23.000000 + 23.000000 = 46.000000
a[567] + b[567] == out[567] is 24.000000 + 24.000000 = 48.000000
a[568] + b[568] == out[568] is 25.000000 + 25.000000 = 50.000000
a[569] + b[569] == out[569] is 26.000000 + 26.000000 = 52.000000
a[570] + b[570] == out[570] is 27.000000 + 27.000000 = 54.000000
a[571] + b[571] == out[571] is 28.000000 + 28.000000 = 56.000000
a[572] + b[572] == out[572] is 29.000000 + 29.000000 = 58.000000
a[573] + b[573] == out[573] is 30.000000 + 30.000000 = 60.000000
a[574] + b[574] == out[574] is 31.000000 + 31.000000 = 62.000000
a[575] + b[575] == out[575] is 32.000000 + 32.000000 = 64.000000
a[576] + b[576] == out[576] is 1.000000 + 1.000000 = 2.000000
a[577] + b[577] == out[577] is 2.000000 + 2.000000 = 4.000000
a[578] + b[578] == out[578] is 3.000000 + 3.000000 = 6.000000
a[579] + b[579] == out[579] is 4.000000 + 4.000000 = 8.000000
a[580] + b[580] == out[580] is 5.000000 + 5.000000 = 10.000000
a[581] + b[581] == out[581] is 6.000000 + 6.000000 = 12.000000
a[582] + b[582] == out[582] is 7.000000 + 7.000000 = 14.000000
a[583] + b[583] == out[583] is 8.000000 + 8.000000 = 16.000000
a[584] + b[584] == out[584] is 9.000000 + 9.000000 = 18.000000
a[585] + b[585] == out[585] is 10.000000 + 10.000000 = 20.000000
a[586] + b[586] == out[586] is 11.000000 + 11.000000 = 22.000000
a[587] + b[587] == out[587] is 12.000000 + 12.000000 = 24.000000
a[588] + b[588] == out[588] is 13.000000 + 13.000000 = 26.000000
a[589] + b[589] == out[589] is 14.000000 + 14.000000 = 28.000000
a[590] + b[590] == out[590] is 15.000000 + 15.000000 = 30.000000
a[591] + b[591] == out[591] is 16.000000 + 16.000000 = 32.000000
a[592] + b[592] == out[592] is 17.000000 + 17.000000 = 34.000000
a[593] + b[593] == out[593] is 18.000000 + 18.000000 = 36.000000
a[594] + b[594] == out[594] is 19.000000 + 19.000000 = 38.000000
a[595] + b[595] == out[595] is 20.000000 + 20.000000 = 40.000000
a[596] + b[596] == out[596] is 21.000000 + 21.000000 = 42.000000
a[597] + b[597] == out[597] is 22.000000 + 22.000000 = 44.000000
a[598] + b[598] == out[598] is 23.000000 + 23.000000 = 46.000000
a[599] + b[599] == out[599] is 24.000000 + 24.000000 = 48.000000
a[600] + b[600] == out[600] is 25.000000 + 25.000000 = 50.000000
a[601] + b[601] == out[601] is 26.000000 + 26.000000 = 52.000000
a[602] + b[602] == out[602] is 27.000000 + 27.000000 = 54.000000
a[603] + b[603] == out[603] is 28.000000 + 28.000000 = 56.000000
a[604] + b[604] == out[604] is 29.000000 + 29.000000 = 58.000000
a[605] + b[605] == out[605] is 30.000000 + 30.000000 = 60.000000
a[606] + b[606] == out[606] is 31.000000 + 31.000000 = 62.000000
a[607] + b[607] == out[607] is 32.000000 + 32.000000 = 64.000000
a[608] + b[608] == out[608] is 1.000000 + 1.000000 = 2.000000
a[609] + b[609] == out[609] is 2.000000 + 2.000000 = 4.000000
a[610] + b[610] == out[610] is 3.000000 + 3.000000 = 6.000000
a[611] + b[611] == out[611] is 4.000000 + 4.000000 = 8.000000
a[612] + b[612] == out[612] is 5.000000 + 5.000000 = 10.000000
a[613] + b[613] == out[613] is 6.000000 + 6.000000 = 12.000000
a[614] + b[614] == out[614] is 7.000000 + 7.000000 = 14.000000
a[615] + b[615] == out[615] is 8.000000 + 8.000000 = 16.000000
a[616] + b[616] == out[616] is 9.000000 + 9.000000 = 18.000000
a[617] + b[617] == out[617] is 10.000000 + 10.000000 = 20.000000
a[618] + b[618] == out[618] is 11.000000 + 11.000000 = 22.000000
a[619] + b[619] == out[619] is 12.000000 + 12.000000 = 24.000000
a[620] + b[620] == out[620] is 13.000000 + 13.000000 = 26.000000
a[621] + b[621] == out[621] is 14.000000 + 14.000000 = 28.000000
a[622] + b[622] == out[622] is 15.000000 + 15.000000 = 30.000000
a[623] + b[623] == out[623] is 16.000000 + 16.000000 = 32.000000
a[624] + b[624] == out[624] is 17.000000 + 17.000000 = 34.000000
a[625] + b[625] == out[625] is 18.000000 + 18.000000 = 36.000000
a[626] + b[626] == out[626] is 19.000000 + 19.000000 = 38.000000
a[627] + b[627] == out[627] is 20.000000 + 20.000000 = 40.000000
a[628] + b[628] == out[628] is 21.000000 + 21.000000 = 42.000000
a[629] + b[629] == out[629] is 22.000000 + 22.000000 = 44.000000
a[630] + b[630] == out[630] is 23.000000 + 23.000000 = 46.000000
a[631] + b[631] == out[631] is 24.000000 + 24.000000 = 48.000000
a[632] + b[632] == out[632] is 25.000000 + 25.000000 = 50.000000
a[633] + b[633] == out[633] is 26.000000 + 26.000000 = 52.000000
a[634] + b[634] == out[634] is 27.000000 + 27.000000 = 54.000000
a[635] + b[635] == out[635] is 28.000000 + 28.000000 = 56.000000
a[636] + b[636] == out[636] is 29.000000 + 29.000000 = 58.000000
a[637] + b[637] == out[637] is 30.000000 + 30.000000 = 60.000000
a[638] + b[638] == out[638] is 31.000000 + 31.000000 = 62.000000
a[639] + b[639] == out[639] is 32.000000 + 32.000000 = 64.000000
a[640] + b[640] == out[640] is 1.000000 + 1.000000 = 2.000000
a[641] + b[641] == out[641] is 2.000000 + 2.000000 = 4.000000
a[642] + b[642] == out[642] is 3.000000 + 3.000000 = 6.000000
a[643] + b[643] == out[643] is 4.000000 + 4.000000 = 8.000000
a[644] + b[644] == out[644] is 5.000000 + 5.000000 = 10.000000
a[645] + b[645] == out[645] is 6.000000 + 6.000000 = 12.000000
a[646] + b[646] == out[646] is 7.000000 + 7.000000 = 14.000000
a[647] + b[647] == out[647] is 8.000000 + 8.000000 = 16.000000
a[648] + b[648] == out[648] is 9.000000 + 9.000000 = 18.000000
a[649] + b[649] == out[649] is 10.000000 + 10.000000 = 20.000000
a[650] + b[650] == out[650] is 11.000000 + 11.000000 = 22.000000
a[651] + b[651] == out[651] is 12.000000 + 12.000000 = 24.000000
a[652] + b[652] == out[652] is 13.000000 + 13.000000 = 26.000000
a[653] + b[653] == out[653] is 14.000000 + 14.000000 = 28.000000
a[654] + b[654] == out[654] is 15.000000 + 15.000000 = 30.000000
a[655] + b[655] == out[655] is 16.000000 + 16.000000 = 32.000000
a[656] + b[656] == out[656] is 17.000000 + 17.000000 = 34.000000
a[657] + b[657] == out[657] is 18.000000 + 18.000000 = 36.000000
a[658] + b[658] == out[658] is 19.000000 + 19.000000 = 38.000000
a[659] + b[659] == out[659] is 20.000000 + 20.000000 = 40.000000
a[660] + b[660] == out[660] is 21.000000 + 21.000000 = 42.000000
a[661] + b[661] == out[661] is 22.000000 + 22.000000 = 44.000000
a[662] + b[662] == out[662] is 23.000000 + 23.000000 = 46.000000
a[663] + b[663] == out[663] is 24.000000 + 24.000000 = 48.000000
a[664] + b[664] == out[664] is 25.000000 + 25.000000 = 50.000000
a[665] + b[665] == out[665] is 26.000000 + 26.000000 = 52.000000
a[666] + b[666] == out[666] is 27.000000 + 27.000000 = 54.000000
a[667] + b[667] == out[667] is 28.000000 + 28.000000 = 56.000000
a[668] + b[668] == out[668] is 29.000000 + 29.000000 = 58.000000
a[669] + b[669] == out[669] is 30.000000 + 30.000000 = 60.000000
a[670] + b[670] == out[670] is 31.000000 + 31.000000 = 62.000000
a[671] + b[671] == out[671] is 32.000000 + 32.000000 = 64.000000
a[672] + b[672] == out[672] is 1.000000 + 1.000000 = 2.000000
a[673] + b[673] == out[673] is 2.000000 + 2.000000 = 4.000000
a[674] + b[674] == out[674] is 3.000000 + 3.000000 = 6.000000
a[675] + b[675] == out[675] is 4.000000 + 4.000000 = 8.000000
a[676] + b[676] == out[676] is 5.000000 + 5.000000 = 10.000000
a[677] + b[677] == out[677] is 6.000000 + 6.000000 = 12.000000
a[678] + b[678] == out[678] is 7.000000 + 7.000000 = 14.000000
a[679] + b[679] == out[679] is 8.000000 + 8.000000 = 16.000000
a[680] + b[680] == out[680] is 9.000000 + 9.000000 = 18.000000
a[681] + b[681] == out[681] is 10.000000 + 10.000000 = 20.000000
a[682] + b[682] == out[682] is 11.000000 + 11.000000 = 22.000000
a[683] + b[683] == out[683] is 12.000000 + 12.000000 = 24.000000
a[684] + b[684] == out[684] is 13.000000 + 13.000000 = 26.000000
a[685] + b[685] == out[685] is 14.000000 + 14.000000 = 28.000000
a[686] + b[686] == out[686] is 15.000000 + 15.000000 = 30.000000
a[687] + b[687] == out[687] is 16.000000 + 16.000000 = 32.000000
a[688] + b[688] == out[688] is 17.000000 + 17.000000 = 34.000000
a[689] + b[689] == out[689] is 18.000000 + 18.000000 = 36.000000
a[690] + b[690] == out[690] is 19.000000 + 19.000000 = 38.000000
a[691] + b[691] == out[691] is 20.000000 + 20.000000 = 40.000000
a[692] + b[692] == out[692] is 21.000000 + 21.000000 = 42.000000
a[693] + b[693] == out[693] is 22.000000 + 22.000000 = 44.000000
a[694] + b[694] == out[694] is 23.000000 + 23.000000 = 46.000000
a[695] + b[695] == out[695] is 24.000000 + 24.000000 = 48.000000
a[696] + b[696] == out[696] is 25.000000 + 25.000000 = 50.000000
a[697] + b[697] == out[697] is 26.000000 + 26.000000 = 52.000000
a[698] + b[698] == out[698] is 27.000000 + 27.000000 = 54.000000
a[699] + b[699] == out[699] is 28.000000 + 28.000000 = 56.000000
a[700] + b[700] == out[700] is 29.000000 + 29.000000 = 58.000000
a[701] + b[701] == out[701] is 30.000000 + 30.000000 = 60.000000
a[702] + b[702] == out[702] is 31.000000 + 31.000000 = 62.000000
a[703] + b[703] == out[703] is 32.000000 + 32.000000 = 64.000000
a[704] + b[704] == out[704] is 1.000000 + 1.000000 = 2.000000
a[705] + b[705] == out[705] is 2.000000 + 2.000000 = 4.000000
a[706] + b[706] == out[706] is 3.000000 + 3.000000 = 6.000000
a[707] + b[707] == out[707] is 4.000000 + 4.000000 = 8.000000
a[708] + b[708] == out[708] is 5.000000 + 5.000000 = 10.000000
a[709] + b[709] == out[709] is 6.000000 + 6.000000 = 12.000000
a[710] + b[710] == out[710] is 7.000000 + 7.000000 = 14.000000
a[711] + b[711] == out[711] is 8.000000 + 8.000000 = 16.000000
a[712] + b[712] == out[712] is 9.000000 + 9.000000 = 18.000000
a[713] + b[713] == out[713] is 10.000000 + 10.000000 = 20.000000
a[714] + b[714] == out[714] is 11.000000 + 11.000000 = 22.000000
a[715] + b[715] == out[715] is 12.000000 + 12.000000 = 24.000000
a[716] + b[716] == out[716] is 13.000000 + 13.000000 = 26.000000
a[717] + b[717] == out[717] is 14.000000 + 14.000000 = 28.000000
a[718] + b[718] == out[718] is 15.000000 + 15.000000 = 30.000000
a[719] + b[719] == out[719] is 16.000000 + 16.000000 = 32.000000
a[720] + b[720] == out[720] is 17.000000 + 17.000000 = 34.000000
a[721] + b[721] == out[721] is 18.000000 + 18.000000 = 36.000000
a[722] + b[722] == out[722] is 19.000000 + 19.000000 = 38.000000
a[723] + b[723] == out[723] is 20.000000 + 20.000000 = 40.000000
a[724] + b[724] == out[724] is 21.000000 + 21.000000 = 42.000000
a[725] + b[725] == out[725] is 22.000000 + 22.000000 = 44.000000
a[726] + b[726] == out[726] is 23.000000 + 23.000000 = 46.000000
a[727] + b[727] == out[727] is 24.000000 + 24.000000 = 48.000000
a[728] + b[728] == out[728] is 25.000000 + 25.000000 = 50.000000
a[729] + b[729] == out[729] is 26.000000 + 26.000000 = 52.000000
a[730] + b[730] == out[730] is 27.000000 + 27.000000 = 54.000000
a[731] + b[731] == out[731] is 28.000000 + 28.000000 = 56.000000
a[732] + b[732] == out[732] is 29.000000 + 29.000000 = 58.000000
a[733] + b[733] == out[733] is 30.000000 + 30.000000 = 60.000000
a[734] + b[734] == out[734] is 31.000000 + 31.000000 = 62.000000
a[735] + b[735] == out[735] is 32.000000 + 32.000000 = 64.000000
a[736] + b[736] == out[736] is 1.000000 + 1.000000 = 2.000000
a[737] + b[737] == out[737] is 2.000000 + 2.000000 = 4.000000
a[738] + b[738] == out[738] is 3.000000 + 3.000000 = 6.000000
a[739] + b[739] == out[739] is 4.000000 + 4.000000 = 8.000000
a[740] + b[740] == out[740] is 5.000000 + 5.000000 = 10.000000
a[741] + b[741] == out[741] is 6.000000 + 6.000000 = 12.000000
a[742] + b[742] == out[742] is 7.000000 + 7.000000 = 14.000000
a[743] + b[743] == out[743] is 8.000000 + 8.000000 = 16.000000
a[744] + b[744] == out[744] is 9.000000 + 9.000000 = 18.000000
a[745] + b[745] == out[745] is 10.000000 + 10.000000 = 20.000000
a[746] + b[746] == out[746] is 11.000000 + 11.000000 = 22.000000
a[747] + b[747] == out[747] is 12.000000 + 12.000000 = 24.000000
a[748] + b[748] == out[748] is 13.000000 + 13.000000 = 26.000000
a[749] + b[749] == out[749] is 14.000000 + 14.000000 = 28.000000
a[750] + b[750] == out[750] is 15.000000 + 15.000000 = 30.000000
a[751] + b[751] == out[751] is 16.000000 + 16.000000 = 32.000000
a[752] + b[752] == out[752] is 17.000000 + 17.000000 = 34.000000
a[753] + b[753] == out[753] is 18.000000 + 18.000000 = 36.000000
a[754] + b[754] == out[754] is 19.000000 + 19.000000 = 38.000000
a[755] + b[755] == out[755] is 20.000000 + 20.000000 = 40.000000
a[756] + b[756] == out[756] is 21.000000 + 21.000000 = 42.000000
a[757] + b[757] == out[757] is 22.000000 + 22.000000 = 44.000000
a[758] + b[758] == out[758] is 23.000000 + 23.000000 = 46.000000
a[759] + b[759] == out[759] is 24.000000 + 24.000000 = 48.000000
a[760] + b[760] == out[760] is 25.000000 + 25.000000 = 50.000000
a[761] + b[761] == out[761] is 26.000000 + 26.000000 = 52.000000
a[762] + b[762] == out[762] is 27.000000 + 27.000000 = 54.000000
a[763] + b[763] == out[763] is 28.000000 + 28.000000 = 56.000000
a[764] + b[764] == out[764] is 29.000000 + 29.000000 = 58.000000
a[765] + b[765] == out[765] is 30.000000 + 30.000000 = 60.000000
a[766] + b[766] == out[766] is 31.000000 + 31.000000 = 62.000000
a[767] + b[767] == out[767] is 32.000000 + 32.000000 = 64.000000
a[768] + b[768] == out[768] is 1.000000 + 1.000000 = 2.000000
a[769] + b[769] == out[769] is 2.000000 + 2.000000 = 4.000000
a[770] + b[770] == out[770] is 3.000000 + 3.000000 = 6.000000
a[771] + b[771] == out[771] is 4.000000 + 4.000000 = 8.000000
a[772] + b[772] == out[772] is 5.000000 + 5.000000 = 10.000000
a[773] + b[773] == out[773] is 6.000000 + 6.000000 = 12.000000
a[774] + b[774] == out[774] is 7.000000 + 7.000000 = 14.000000
a[775] + b[775] == out[775] is 8.000000 + 8.000000 = 16.000000
a[776] + b[776] == out[776] is 9.000000 + 9.000000 = 18.000000
a[777] + b[777] == out[777] is 10.000000 + 10.000000 = 20.000000
a[778] + b[778] == out[778] is 11.000000 + 11.000000 = 22.000000
a[779] + b[779] == out[779] is 12.000000 + 12.000000 = 24.000000
a[780] + b[780] == out[780] is 13.000000 + 13.000000 = 26.000000
a[781] + b[781] == out[781] is 14.000000 + 14.000000 = 28.000000
a[782] + b[782] == out[782] is 15.000000 + 15.000000 = 30.000000
a[783] + b[783] == out[783] is 16.000000 + 16.000000 = 32.000000
a[784] + b[784] == out[784] is 17.000000 + 17.000000 = 34.000000
a[785] + b[785] == out[785] is 18.000000 + 18.000000 = 36.000000
a[786] + b[786] == out[786] is 19.000000 + 19.000000 = 38.000000
a[787] + b[787] == out[787] is 20.000000 + 20.000000 = 40.000000
a[788] + b[788] == out[788] is 21.000000 + 21.000000 = 42.000000
a[789] + b[789] == out[789] is 22.000000 + 22.000000 = 44.000000
a[790] + b[790] == out[790] is 23.000000 + 23.000000 = 46.000000
a[791] + b[791] == out[791] is 24.000000 + 24.000000 = 48.000000
a[792] + b[792] == out[792] is 25.000000 + 25.000000 = 50.000000
a[793] + b[793] == out[793] is 26.000000 + 26.000000 = 52.000000
a[794] + b[794] == out[794] is 27.000000 + 27.000000 = 54.000000
a[795] + b[795] == out[795] is 28.000000 + 28.000000 = 56.000000
a[796] + b[796] == out[796] is 29.000000 + 29.000000 = 58.000000
a[797] + b[797] == out[797] is 30.000000 + 30.000000 = 60.000000
a[798] + b[798] == out[798] is 31.000000 + 31.000000 = 62.000000
a[799] + b[799] == out[799] is 32.000000 + 32.000000 = 64.000000
a[800] + b[800] == out[800] is 1.000000 + 1.000000 = 2.000000
a[801] + b[801] == out[801] is 2.000000 + 2.000000 = 4.000000
a[802] + b[802] == out[802] is 3.000000 + 3.000000 = 6.000000
a[803] + b[803] == out[803] is 4.000000 + 4.000000 = 8.000000
a[804] + b[804] == out[804] is 5.000000 + 5.000000 = 10.000000
a[805] + b[805] == out[805] is 6.000000 + 6.000000 = 12.000000
a[806] + b[806] == out[806] is 7.000000 + 7.000000 = 14.000000
a[807] + b[807] == out[807] is 8.000000 + 8.000000 = 16.000000
a[808] + b[808] == out[808] is 9.000000 + 9.000000 = 18.000000
a[809] + b[809] == out[809] is 10.000000 + 10.000000 = 20.000000
a[810] + b[810] == out[810] is 11.000000 + 11.000000 = 22.000000
a[811] + b[811] == out[811] is 12.000000 + 12.000000 = 24.000000
a[812] + b[812] == out[812] is 13.000000 + 13.000000 = 26.000000
a[813] + b[813] == out[813] is 14.000000 + 14.000000 = 28.000000
a[814] + b[814] == out[814] is 15.000000 + 15.000000 = 30.000000
a[815] + b[815] == out[815] is 16.000000 + 16.000000 = 32.000000
a[816] + b[816] == out[816] is 17.000000 + 17.000000 = 34.000000
a[817] + b[817] == out[817] is 18.000000 + 18.000000 = 36.000000
a[818] + b[818] == out[818] is 19.000000 + 19.000000 = 38.000000
a[819] + b[819] == out[819] is 20.000000 + 20.000000 = 40.000000
a[820] + b[820] == out[820] is 21.000000 + 21.000000 = 42.000000
a[821] + b[821] == out[821] is 22.000000 + 22.000000 = 44.000000
a[822] + b[822] == out[822] is 23.000000 + 23.000000 = 46.000000
a[823] + b[823] == out[823] is 24.000000 + 24.000000 = 48.000000
a[824] + b[824] == out[824] is 25.000000 + 25.000000 = 50.000000
a[825] + b[825] == out[825] is 26.000000 + 26.000000 = 52.000000
a[826] + b[826] == out[826] is 27.000000 + 27.000000 = 54.000000
a[827] + b[827] == out[827] is 28.000000 + 28.000000 = 56.000000
a[828] + b[828] == out[828] is 29.000000 + 29.000000 = 58.000000
a[829] + b[829] == out[829] is 30.000000 + 30.000000 = 60.000000
a[830] + b[830] == out[830] is 31.000000 + 31.000000 = 62.000000
a[831] + b[831] == out[831] is 32.000000 + 32.000000 = 64.000000
a[832] + b[832] == out[832] is 1.000000 + 1.000000 = 2.000000
a[833] + b[833] == out[833] is 2.000000 + 2.000000 = 4.000000
a[834] + b[834] == out[834] is 3.000000 + 3.000000 = 6.000000
a[835] + b[835] == out[835] is 4.000000 + 4.000000 = 8.000000
a[836] + b[836] == out[836] is 5.000000 + 5.000000 = 10.000000
a[837] + b[837] == out[837] is 6.000000 + 6.000000 = 12.000000
a[838] + b[838] == out[838] is 7.000000 + 7.000000 = 14.000000
a[839] + b[839] == out[839] is 8.000000 + 8.000000 = 16.000000
a[840] + b[840] == out[840] is 9.000000 + 9.000000 = 18.000000
a[841] + b[841] == out[841] is 10.000000 + 10.000000 = 20.000000
a[842] + b[842] == out[842] is 11.000000 + 11.000000 = 22.000000
a[843] + b[843] == out[843] is 12.000000 + 12.000000 = 24.000000
a[844] + b[844] == out[844] is 13.000000 + 13.000000 = 26.000000
a[845] + b[845] == out[845] is 14.000000 + 14.000000 = 28.000000
a[846] + b[846] == out[846] is 15.000000 + 15.000000 = 30.000000
a[847] + b[847] == out[847] is 16.000000 + 16.000000 = 32.000000
a[848] + b[848] == out[848] is 17.000000 + 17.000000 = 34.000000
a[849] + b[849] == out[849] is 18.000000 + 18.000000 = 36.000000
a[850] + b[850] == out[850] is 19.000000 + 19.000000 = 38.000000
a[851] + b[851] == out[851] is 20.000000 + 20.000000 = 40.000000
a[852] + b[852] == out[852] is 21.000000 + 21.000000 = 42.000000
a[853] + b[853] == out[853] is 22.000000 + 22.000000 = 44.000000
a[854] + b[854] == out[854] is 23.000000 + 23.000000 = 46.000000
a[855] + b[855] == out[855] is 24.000000 + 24.000000 = 48.000000
a[856] + b[856] == out[856] is 25.000000 + 25.000000 = 50.000000
a[857] + b[857] == out[857] is 26.000000 + 26.000000 = 52.000000
a[858] + b[858] == out[858] is 27.000000 + 27.000000 = 54.000000
a[859] + b[859] == out[859] is 28.000000 + 28.000000 = 56.000000
a[860] + b[860] == out[860] is 29.000000 + 29.000000 = 58.000000
a[861] + b[861] == out[861] is 30.000000 + 30.000000 = 60.000000
a[862] + b[862] == out[862] is 31.000000 + 31.000000 = 62.000000
a[863] + b[863] == out[863] is 32.000000 + 32.000000 = 64.000000
a[864] + b[864] == out[864] is 1.000000 + 1.000000 = 2.000000
a[865] + b[865] == out[865] is 2.000000 + 2.000000 = 4.000000
a[866] + b[866] == out[866] is 3.000000 + 3.000000 = 6.000000
a[867] + b[867] == out[867] is 4.000000 + 4.000000 = 8.000000
a[868] + b[868] == out[868] is 5.000000 + 5.000000 = 10.000000
a[869] + b[869] == out[869] is 6.000000 + 6.000000 = 12.000000
a[870] + b[870] == out[870] is 7.000000 + 7.000000 = 14.000000
a[871] + b[871] == out[871] is 8.000000 + 8.000000 = 16.000000
a[872] + b[872] == out[872] is 9.000000 + 9.000000 = 18.000000
a[873] + b[873] == out[873] is 10.000000 + 10.000000 = 20.000000
a[874] + b[874] == out[874] is 11.000000 + 11.000000 = 22.000000
a[875] + b[875] == out[875] is 12.000000 + 12.000000 = 24.000000
a[876] + b[876] == out[876] is 13.000000 + 13.000000 = 26.000000
a[877] + b[877] == out[877] is 14.000000 + 14.000000 = 28.000000
a[878] + b[878] == out[878] is 15.000000 + 15.000000 = 30.000000
a[879] + b[879] == out[879] is 16.000000 + 16.000000 = 32.000000
a[880] + b[880] == out[880] is 17.000000 + 17.000000 = 34.000000
a[881] + b[881] == out[881] is 18.000000 + 18.000000 = 36.000000
a[882] + b[882] == out[882] is 19.000000 + 19.000000 = 38.000000
a[883] + b[883] == out[883] is 20.000000 + 20.000000 = 40.000000
a[884] + b[884] == out[884] is 21.000000 + 21.000000 = 42.000000
a[885] + b[885] == out[885] is 22.000000 + 22.000000 = 44.000000
a[886] + b[886] == out[886] is 23.000000 + 23.000000 = 46.000000
a[887] + b[887] == out[887] is 24.000000 + 24.000000 = 48.000000
a[888] + b[888] == out[888] is 25.000000 + 25.000000 = 50.000000
a[889] + b[889] == out[889] is 26.000000 + 26.000000 = 52.000000
a[890] + b[890] == out[890] is 27.000000 + 27.000000 = 54.000000
a[891] + b[891] == out[891] is 28.000000 + 28.000000 = 56.000000
a[892] + b[892] == out[892] is 29.000000 + 29.000000 = 58.000000
a[893] + b[893] == out[893] is 30.000000 + 30.000000 = 60.000000
a[894] + b[894] == out[894] is 31.000000 + 31.000000 = 62.000000
a[895] + b[895] == out[895] is 32.000000 + 32.000000 = 64.000000
a[896] + b[896] == out[896] is 1.000000 + 1.000000 = 2.000000
a[897] + b[897] == out[897] is 2.000000 + 2.000000 = 4.000000
a[898] + b[898] == out[898] is 3.000000 + 3.000000 = 6.000000
a[899] + b[899] == out[899] is 4.000000 + 4.000000 = 8.000000
a[900] + b[900] == out[900] is 5.000000 + 5.000000 = 10.000000
a[901] + b[901] == out[901] is 6.000000 + 6.000000 = 12.000000
a[902] + b[902] == out[902] is 7.000000 + 7.000000 = 14.000000
a[903] + b[903] == out[903] is 8.000000 + 8.000000 = 16.000000
a[904] + b[904] == out[904] is 9.000000 + 9.000000 = 18.000000
a[905] + b[905] == out[905] is 10.000000 + 10.000000 = 20.000000
a[906] + b[906] == out[906] is 11.000000 + 11.000000 = 22.000000
a[907] + b[907] == out[907] is 12.000000 + 12.000000 = 24.000000
a[908] + b[908] == out[908] is 13.000000 + 13.000000 = 26.000000
a[909] + b[909] == out[909] is 14.000000 + 14.000000 = 28.000000
a[910] + b[910] == out[910] is 15.000000 + 15.000000 = 30.000000
a[911] + b[911] == out[911] is 16.000000 + 16.000000 = 32.000000
a[912] + b[912] == out[912] is 17.000000 + 17.000000 = 34.000000
a[913] + b[913] == out[913] is 18.000000 + 18.000000 = 36.000000
a[914] + b[914] == out[914] is 19.000000 + 19.000000 = 38.000000
a[915] + b[915] == out[915] is 20.000000 + 20.000000 = 40.000000
a[916] + b[916] == out[916] is 21.000000 + 21.000000 = 42.000000
a[917] + b[917] == out[917] is 22.000000 + 22.000000 = 44.000000
a[918] + b[918] == out[918] is 23.000000 + 23.000000 = 46.000000
a[919] + b[919] == out[919] is 24.000000 + 24.000000 = 48.000000
a[920] + b[920] == out[920] is 25.000000 + 25.000000 = 50.000000
a[921] + b[921] == out[921] is 26.000000 + 26.000000 = 52.000000
a[922] + b[922] == out[922] is 27.000000 + 27.000000 = 54.000000
a[923] + b[923] == out[923] is 28.000000 + 28.000000 = 56.000000
a[924] + b[924] == out[924] is 29.000000 + 29.000000 = 58.000000
a[925] + b[925] == out[925] is 30.000000 + 30.000000 = 60.000000
a[926] + b[926] == out[926] is 31.000000 + 31.000000 = 62.000000
a[927] + b[927] == out[927] is 32.000000 + 32.000000 = 64.000000
a[928] + b[928] == out[928] is 1.000000 + 1.000000 = 2.000000
a[929] + b[929] == out[929] is 2.000000 + 2.000000 = 4.000000
a[930] + b[930] == out[930] is 3.000000 + 3.000000 = 6.000000
a[931] + b[931] == out[931] is 4.000000 + 4.000000 = 8.000000
a[932] + b[932] == out[932] is 5.000000 + 5.000000 = 10.000000
a[933] + b[933] == out[933] is 6.000000 + 6.000000 = 12.000000
a[934] + b[934] == out[934] is 7.000000 + 7.000000 = 14.000000
a[935] + b[935] == out[935] is 8.000000 + 8.000000 = 16.000000
a[936] + b[936] == out[936] is 9.000000 + 9.000000 = 18.000000
a[937] + b[937] == out[937] is 10.000000 + 10.000000 = 20.000000
a[938] + b[938] == out[938] is 11.000000 + 11.000000 = 22.000000
a[939] + b[939] == out[939] is 12.000000 + 12.000000 = 24.000000
a[940] + b[940] == out[940] is 13.000000 + 13.000000 = 26.000000
a[941] + b[941] == out[941] is 14.000000 + 14.000000 = 28.000000
a[942] + b[942] == out[942] is 15.000000 + 15.000000 = 30.000000
a[943] + b[943] == out[943] is 16.000000 + 16.000000 = 32.000000
a[944] + b[944] == out[944] is 17.000000 + 17.000000 = 34.000000
a[945] + b[945] == out[945] is 18.000000 + 18.000000 = 36.000000
a[946] + b[946] == out[946] is 19.000000 + 19.000000 = 38.000000
a[947] + b[947] == out[947] is 20.000000 + 20.000000 = 40.000000
a[948] + b[948] == out[948] is 21.000000 + 21.000000 = 42.000000
a[949] + b[949] == out[949] is 22.000000 + 22.000000 = 44.000000
a[950] + b[950] == out[950] is 23.000000 + 23.000000 = 46.000000
a[951] + b[951] == out[951] is 24.000000 + 24.000000 = 48.000000
a[952] + b[952] == out[952] is 25.000000 + 25.000000 = 50.000000
a[953] + b[953] == out[953] is 26.000000 + 26.000000 = 52.000000
a[954] + b[954] == out[954] is 27.000000 + 27.000000 = 54.000000
a[955] + b[955] == out[955] is 28.000000 + 28.000000 = 56.000000
a[956] + b[956] == out[956] is 29.000000 + 29.000000 = 58.000000
a[957] + b[957] == out[957] is 30.000000 + 30.000000 = 60.000000
a[958] + b[958] == out[958] is 31.000000 + 31.000000 = 62.000000
a[959] + b[959] == out[959] is 32.000000 + 32.000000 = 64.000000
a[960] + b[960] == out[960] is 1.000000 + 1.000000 = 2.000000
a[961] + b[961] == out[961] is 2.000000 + 2.000000 = 4.000000
a[962] + b[962] == out[962] is 3.000000 + 3.000000 = 6.000000
a[963] + b[963] == out[963] is 4.000000 + 4.000000 = 8.000000
a[964] + b[964] == out[964] is 5.000000 + 5.000000 = 10.000000
a[965] + b[965] == out[965] is 6.000000 + 6.000000 = 12.000000
a[966] + b[966] == out[966] is 7.000000 + 7.000000 = 14.000000
a[967] + b[967] == out[967] is 8.000000 + 8.000000 = 16.000000
a[968] + b[968] == out[968] is 9.000000 + 9.000000 = 18.000000
a[969] + b[969] == out[969] is 10.000000 + 10.000000 = 20.000000
a[970] + b[970] == out[970] is 11.000000 + 11.000000 = 22.000000
a[971] + b[971] == out[971] is 12.000000 + 12.000000 = 24.000000
a[972] + b[972] == out[972] is 13.000000 + 13.000000 = 26.000000
a[973] + b[973] == out[973] is 14.000000 + 14.000000 = 28.000000
a[974] + b[974] == out[974] is 15.000000 + 15.000000 = 30.000000
a[975] + b[975] == out[975] is 16.000000 + 16.000000 = 32.000000
a[976] + b[976] == out[976] is 17.000000 + 17.000000 = 34.000000
a[977] + b[977] == out[977] is 18.000000 + 18.000000 = 36.000000
a[978] + b[978] == out[978] is 19.000000 + 19.000000 = 38.000000
a[979] + b[979] == out[979] is 20.000000 + 20.000000 = 40.000000
a[980] + b[980] == out[980] is 21.000000 + 21.000000 = 42.000000
a[981] + b[981] == out[981] is 22.000000 + 22.000000 = 44.000000
a[982] + b[982] == out[982] is 23.000000 + 23.000000 = 46.000000
a[983] + b[983] == out[983] is 24.000000 + 24.000000 = 48.000000
a[984] + b[984] == out[984] is 25.000000 + 25.000000 = 50.000000
a[985] + b[985] == out[985] is 26.000000 + 26.000000 = 52.000000
a[986] + b[986] == out[986] is 27.000000 + 27.000000 = 54.000000
a[987] + b[987] == out[987] is 28.000000 + 28.000000 = 56.000000
a[988] + b[988] == out[988] is 29.000000 + 29.000000 = 58.000000
a[989] + b[989] == out[989] is 30.000000 + 30.000000 = 60.000000
a[990] + b[990] == out[990] is 31.000000 + 31.000000 = 62.000000
a[991] + b[991] == out[991] is 32.000000 + 32.000000 = 64.000000
a[992] + b[992] == out[992] is 1.000000 + 1.000000 = 2.000000
a[993] + b[993] == out[993] is 2.000000 + 2.000000 = 4.000000
a[994] + b[994] == out[994] is 3.000000 + 3.000000 = 6.000000
a[995] + b[995] == out[995] is 4.000000 + 4.000000 = 8.000000
a[996] + b[996] == out[996] is 5.000000 + 5.000000 = 10.000000
a[997] + b[997] == out[997] is 6.000000 + 6.000000 = 12.000000
a[998] + b[998] == out[998] is 7.000000 + 7.000000 = 14.000000
a[999] + b[999] == out[999] is 8.000000 + 8.000000 = 16.000000
a[1000] + b[1000] == out[1000] is 9.000000 + 9.000000 = 18.000000
a[1001] + b[1001] == out[1001] is 10.000000 + 10.000000 = 20.000000
a[1002] + b[1002] == out[1002] is 11.000000 + 11.000000 = 22.000000
a[1003] + b[1003] == out[1003] is 12.000000 + 12.000000 = 24.000000
a[1004] + b[1004] == out[1004] is 13.000000 + 13.000000 = 26.000000
a[1005] + b[1005] == out[1005] is 14.000000 + 14.000000 = 28.000000
a[1006] + b[1006] == out[1006] is 15.000000 + 15.000000 = 30.000000
a[1007] + b[1007] == out[1007] is 16.000000 + 16.000000 = 32.000000
a[1008] + b[1008] == out[1008] is 17.000000 + 17.000000 = 34.000000
a[1009] + b[1009] == out[1009] is 18.000000 + 18.000000 = 36.000000
a[1010] + b[1010] == out[1010] is 19.000000 + 19.000000 = 38.000000
a[1011] + b[1011] == out[1011] is 20.000000 + 20.000000 = 40.000000
a[1012] + b[1012] == out[1012] is 21.000000 + 21.000000 = 42.000000
a[1013] + b[1013] == out[1013] is 22.000000 + 22.000000 = 44.000000
a[1014] + b[1014] == out[1014] is 23.000000 + 23.000000 = 46.000000
a[1015] + b[1015] == out[1015] is 24.000000 + 24.000000 = 48.000000
a[1016] + b[1016] == out[1016] is 25.000000 + 25.000000 = 50.000000
a[1017] + b[1017] == out[1017] is 26.000000 + 26.000000 = 52.000000
a[1018] + b[1018] == out[1018] is 27.000000 + 27.000000 = 54.000000
a[1019] + b[1019] == out[1019] is 28.000000 + 28.000000 = 56.000000
a[1020] + b[1020] == out[1020] is 29.000000 + 29.000000 = 58.000000
a[1021] + b[1021] == out[1021] is 30.000000 + 30.000000 = 60.000000
a[1022] + b[1022] == out[1022] is 31.000000 + 31.000000 = 62.000000
a[1023] + b[1023] == out[1023] is 32.000000 + 32.000000 = 64.000000
Passed

dim 2, grid 1, block NxN for matrix with one dim array

#include <stdio.h>
#include <cuda.h>
#include <assert.h>
#include <cuda_runtime.h>
#include <curand_kernel.h>
#define n 32
#define N n*n
__global__ void add(float *a, float *b, float *c){
  int tidx = threadIdx.x;
  int tidy = threadIdx.y;
  for(int i = 0; i <= n; i++){
    c[tidx + tidy*i] = a[tidx + tidy*i] + b[tidx + tidy*i];
  }
}
int main()
{
  float a[N], b[N], out[N];
  float *d_a, *d_b, *d_out; 

  for(int i = 0; i < n; i++){
    for (int j = 0; j < n; j++){
      a[i+j*n] = 1.0f;
      b[i+j*n] = 2.0f;
    }
  }

  // Allocate device memory 
  cudaMalloc((void**)&d_a, sizeof(float) * N);
  cudaMalloc((void**)&d_b, sizeof(float) * N);
  cudaMalloc((void**)&d_out, sizeof(float) * N);

  // Transfer data from host to device memory
  cudaMemcpy(d_a, a, sizeof(float) * N, cudaMemcpyHostToDevice);
  cudaMemcpy(d_b, b, sizeof(float) * N, cudaMemcpyHostToDevice);

  dim3 BlockPerGrid(1, 1, 1);
  dim3 ThreadsPerBlock(n, n, 1);
  add <<< BlockPerGrid, ThreadsPerBlock >>>(d_a, d_b, d_out);
  cudaMemcpy(out, d_out, sizeof(int) * N, cudaMemcpyDeviceToHost);
  for(int i=0; i < N; i++){
    printf("a[%d] + b[%d] == out[%d] is %f + %f = %f\n", i,i,i, a[i], b[i], out[i]);
  }
  printf("Passed\n");
  cudaFree(d_out);
  cudaFree(d_b);
  cudaFree(d_a);
  return 0;
}

cd babel
nvcc gpu_vector_add_dim2_grid1_blockNxN_matrix_witharray.cu -o gpu_vector_add_dim2_grid1_blockNxN_matrix_witharray
./gpu_vector_add_dim2_grid1_blockNxN_matrix_witharray
a[0] + b[0] == out[0] is 1.000000 + 2.000000 = 3.000000
a[1] + b[1] == out[1] is 1.000000 + 2.000000 = 3.000000
a[2] + b[2] == out[2] is 1.000000 + 2.000000 = 3.000000
a[3] + b[3] == out[3] is 1.000000 + 2.000000 = 3.000000
a[4] + b[4] == out[4] is 1.000000 + 2.000000 = 3.000000
a[5] + b[5] == out[5] is 1.000000 + 2.000000 = 3.000000
a[6] + b[6] == out[6] is 1.000000 + 2.000000 = 3.000000
a[7] + b[7] == out[7] is 1.000000 + 2.000000 = 3.000000
a[8] + b[8] == out[8] is 1.000000 + 2.000000 = 3.000000
a[9] + b[9] == out[9] is 1.000000 + 2.000000 = 3.000000
a[10] + b[10] == out[10] is 1.000000 + 2.000000 = 3.000000
a[11] + b[11] == out[11] is 1.000000 + 2.000000 = 3.000000
a[12] + b[12] == out[12] is 1.000000 + 2.000000 = 3.000000
a[13] + b[13] == out[13] is 1.000000 + 2.000000 = 3.000000
a[14] + b[14] == out[14] is 1.000000 + 2.000000 = 3.000000
a[15] + b[15] == out[15] is 1.000000 + 2.000000 = 3.000000
a[16] + b[16] == out[16] is 1.000000 + 2.000000 = 3.000000
a[17] + b[17] == out[17] is 1.000000 + 2.000000 = 3.000000
a[18] + b[18] == out[18] is 1.000000 + 2.000000 = 3.000000
a[19] + b[19] == out[19] is 1.000000 + 2.000000 = 3.000000
a[20] + b[20] == out[20] is 1.000000 + 2.000000 = 3.000000
a[21] + b[21] == out[21] is 1.000000 + 2.000000 = 3.000000
a[22] + b[22] == out[22] is 1.000000 + 2.000000 = 3.000000
a[23] + b[23] == out[23] is 1.000000 + 2.000000 = 3.000000
a[24] + b[24] == out[24] is 1.000000 + 2.000000 = 3.000000
a[25] + b[25] == out[25] is 1.000000 + 2.000000 = 3.000000
a[26] + b[26] == out[26] is 1.000000 + 2.000000 = 3.000000
a[27] + b[27] == out[27] is 1.000000 + 2.000000 = 3.000000
a[28] + b[28] == out[28] is 1.000000 + 2.000000 = 3.000000
a[29] + b[29] == out[29] is 1.000000 + 2.000000 = 3.000000
a[30] + b[30] == out[30] is 1.000000 + 2.000000 = 3.000000
a[31] + b[31] == out[31] is 1.000000 + 2.000000 = 3.000000
a[32] + b[32] == out[32] is 1.000000 + 2.000000 = 3.000000
a[33] + b[33] == out[33] is 1.000000 + 2.000000 = 3.000000
a[34] + b[34] == out[34] is 1.000000 + 2.000000 = 3.000000
a[35] + b[35] == out[35] is 1.000000 + 2.000000 = 3.000000
a[36] + b[36] == out[36] is 1.000000 + 2.000000 = 3.000000
a[37] + b[37] == out[37] is 1.000000 + 2.000000 = 3.000000
a[38] + b[38] == out[38] is 1.000000 + 2.000000 = 3.000000
a[39] + b[39] == out[39] is 1.000000 + 2.000000 = 3.000000
a[40] + b[40] == out[40] is 1.000000 + 2.000000 = 3.000000
a[41] + b[41] == out[41] is 1.000000 + 2.000000 = 3.000000
a[42] + b[42] == out[42] is 1.000000 + 2.000000 = 3.000000
a[43] + b[43] == out[43] is 1.000000 + 2.000000 = 3.000000
a[44] + b[44] == out[44] is 1.000000 + 2.000000 = 3.000000
a[45] + b[45] == out[45] is 1.000000 + 2.000000 = 3.000000
a[46] + b[46] == out[46] is 1.000000 + 2.000000 = 3.000000
a[47] + b[47] == out[47] is 1.000000 + 2.000000 = 3.000000
a[48] + b[48] == out[48] is 1.000000 + 2.000000 = 3.000000
a[49] + b[49] == out[49] is 1.000000 + 2.000000 = 3.000000
a[50] + b[50] == out[50] is 1.000000 + 2.000000 = 3.000000
a[51] + b[51] == out[51] is 1.000000 + 2.000000 = 3.000000
a[52] + b[52] == out[52] is 1.000000 + 2.000000 = 3.000000
a[53] + b[53] == out[53] is 1.000000 + 2.000000 = 3.000000
a[54] + b[54] == out[54] is 1.000000 + 2.000000 = 3.000000
a[55] + b[55] == out[55] is 1.000000 + 2.000000 = 3.000000
a[56] + b[56] == out[56] is 1.000000 + 2.000000 = 3.000000
a[57] + b[57] == out[57] is 1.000000 + 2.000000 = 3.000000
a[58] + b[58] == out[58] is 1.000000 + 2.000000 = 3.000000
a[59] + b[59] == out[59] is 1.000000 + 2.000000 = 3.000000
a[60] + b[60] == out[60] is 1.000000 + 2.000000 = 3.000000
a[61] + b[61] == out[61] is 1.000000 + 2.000000 = 3.000000
a[62] + b[62] == out[62] is 1.000000 + 2.000000 = 3.000000
a[63] + b[63] == out[63] is 1.000000 + 2.000000 = 3.000000
a[64] + b[64] == out[64] is 1.000000 + 2.000000 = 3.000000
a[65] + b[65] == out[65] is 1.000000 + 2.000000 = 3.000000
a[66] + b[66] == out[66] is 1.000000 + 2.000000 = 3.000000
a[67] + b[67] == out[67] is 1.000000 + 2.000000 = 3.000000
a[68] + b[68] == out[68] is 1.000000 + 2.000000 = 3.000000
a[69] + b[69] == out[69] is 1.000000 + 2.000000 = 3.000000
a[70] + b[70] == out[70] is 1.000000 + 2.000000 = 3.000000
a[71] + b[71] == out[71] is 1.000000 + 2.000000 = 3.000000
a[72] + b[72] == out[72] is 1.000000 + 2.000000 = 3.000000
a[73] + b[73] == out[73] is 1.000000 + 2.000000 = 3.000000
a[74] + b[74] == out[74] is 1.000000 + 2.000000 = 3.000000
a[75] + b[75] == out[75] is 1.000000 + 2.000000 = 3.000000
a[76] + b[76] == out[76] is 1.000000 + 2.000000 = 3.000000
a[77] + b[77] == out[77] is 1.000000 + 2.000000 = 3.000000
a[78] + b[78] == out[78] is 1.000000 + 2.000000 = 3.000000
a[79] + b[79] == out[79] is 1.000000 + 2.000000 = 3.000000
a[80] + b[80] == out[80] is 1.000000 + 2.000000 = 3.000000
a[81] + b[81] == out[81] is 1.000000 + 2.000000 = 3.000000
a[82] + b[82] == out[82] is 1.000000 + 2.000000 = 3.000000
a[83] + b[83] == out[83] is 1.000000 + 2.000000 = 3.000000
a[84] + b[84] == out[84] is 1.000000 + 2.000000 = 3.000000
a[85] + b[85] == out[85] is 1.000000 + 2.000000 = 3.000000
a[86] + b[86] == out[86] is 1.000000 + 2.000000 = 3.000000
a[87] + b[87] == out[87] is 1.000000 + 2.000000 = 3.000000
a[88] + b[88] == out[88] is 1.000000 + 2.000000 = 3.000000
a[89] + b[89] == out[89] is 1.000000 + 2.000000 = 3.000000
a[90] + b[90] == out[90] is 1.000000 + 2.000000 = 3.000000
a[91] + b[91] == out[91] is 1.000000 + 2.000000 = 3.000000
a[92] + b[92] == out[92] is 1.000000 + 2.000000 = 3.000000
a[93] + b[93] == out[93] is 1.000000 + 2.000000 = 3.000000
a[94] + b[94] == out[94] is 1.000000 + 2.000000 = 3.000000
a[95] + b[95] == out[95] is 1.000000 + 2.000000 = 3.000000
a[96] + b[96] == out[96] is 1.000000 + 2.000000 = 3.000000
a[97] + b[97] == out[97] is 1.000000 + 2.000000 = 3.000000
a[98] + b[98] == out[98] is 1.000000 + 2.000000 = 3.000000
a[99] + b[99] == out[99] is 1.000000 + 2.000000 = 3.000000
a[100] + b[100] == out[100] is 1.000000 + 2.000000 = 3.000000
a[101] + b[101] == out[101] is 1.000000 + 2.000000 = 3.000000
a[102] + b[102] == out[102] is 1.000000 + 2.000000 = 3.000000
a[103] + b[103] == out[103] is 1.000000 + 2.000000 = 3.000000
a[104] + b[104] == out[104] is 1.000000 + 2.000000 = 3.000000
a[105] + b[105] == out[105] is 1.000000 + 2.000000 = 3.000000
a[106] + b[106] == out[106] is 1.000000 + 2.000000 = 3.000000
a[107] + b[107] == out[107] is 1.000000 + 2.000000 = 3.000000
a[108] + b[108] == out[108] is 1.000000 + 2.000000 = 3.000000
a[109] + b[109] == out[109] is 1.000000 + 2.000000 = 3.000000
a[110] + b[110] == out[110] is 1.000000 + 2.000000 = 3.000000
a[111] + b[111] == out[111] is 1.000000 + 2.000000 = 3.000000
a[112] + b[112] == out[112] is 1.000000 + 2.000000 = 3.000000
a[113] + b[113] == out[113] is 1.000000 + 2.000000 = 3.000000
a[114] + b[114] == out[114] is 1.000000 + 2.000000 = 3.000000
a[115] + b[115] == out[115] is 1.000000 + 2.000000 = 3.000000
a[116] + b[116] == out[116] is 1.000000 + 2.000000 = 3.000000
a[117] + b[117] == out[117] is 1.000000 + 2.000000 = 3.000000
a[118] + b[118] == out[118] is 1.000000 + 2.000000 = 3.000000
a[119] + b[119] == out[119] is 1.000000 + 2.000000 = 3.000000
a[120] + b[120] == out[120] is 1.000000 + 2.000000 = 3.000000
a[121] + b[121] == out[121] is 1.000000 + 2.000000 = 3.000000
a[122] + b[122] == out[122] is 1.000000 + 2.000000 = 3.000000
a[123] + b[123] == out[123] is 1.000000 + 2.000000 = 3.000000
a[124] + b[124] == out[124] is 1.000000 + 2.000000 = 3.000000
a[125] + b[125] == out[125] is 1.000000 + 2.000000 = 3.000000
a[126] + b[126] == out[126] is 1.000000 + 2.000000 = 3.000000
a[127] + b[127] == out[127] is 1.000000 + 2.000000 = 3.000000
a[128] + b[128] == out[128] is 1.000000 + 2.000000 = 3.000000
a[129] + b[129] == out[129] is 1.000000 + 2.000000 = 3.000000
a[130] + b[130] == out[130] is 1.000000 + 2.000000 = 3.000000
a[131] + b[131] == out[131] is 1.000000 + 2.000000 = 3.000000
a[132] + b[132] == out[132] is 1.000000 + 2.000000 = 3.000000
a[133] + b[133] == out[133] is 1.000000 + 2.000000 = 3.000000
a[134] + b[134] == out[134] is 1.000000 + 2.000000 = 3.000000
a[135] + b[135] == out[135] is 1.000000 + 2.000000 = 3.000000
a[136] + b[136] == out[136] is 1.000000 + 2.000000 = 3.000000
a[137] + b[137] == out[137] is 1.000000 + 2.000000 = 3.000000
a[138] + b[138] == out[138] is 1.000000 + 2.000000 = 3.000000
a[139] + b[139] == out[139] is 1.000000 + 2.000000 = 3.000000
a[140] + b[140] == out[140] is 1.000000 + 2.000000 = 3.000000
a[141] + b[141] == out[141] is 1.000000 + 2.000000 = 3.000000
a[142] + b[142] == out[142] is 1.000000 + 2.000000 = 3.000000
a[143] + b[143] == out[143] is 1.000000 + 2.000000 = 3.000000
a[144] + b[144] == out[144] is 1.000000 + 2.000000 = 3.000000
a[145] + b[145] == out[145] is 1.000000 + 2.000000 = 3.000000
a[146] + b[146] == out[146] is 1.000000 + 2.000000 = 3.000000
a[147] + b[147] == out[147] is 1.000000 + 2.000000 = 3.000000
a[148] + b[148] == out[148] is 1.000000 + 2.000000 = 3.000000
a[149] + b[149] == out[149] is 1.000000 + 2.000000 = 3.000000
a[150] + b[150] == out[150] is 1.000000 + 2.000000 = 3.000000
a[151] + b[151] == out[151] is 1.000000 + 2.000000 = 3.000000
a[152] + b[152] == out[152] is 1.000000 + 2.000000 = 3.000000
a[153] + b[153] == out[153] is 1.000000 + 2.000000 = 3.000000
a[154] + b[154] == out[154] is 1.000000 + 2.000000 = 3.000000
a[155] + b[155] == out[155] is 1.000000 + 2.000000 = 3.000000
a[156] + b[156] == out[156] is 1.000000 + 2.000000 = 3.000000
a[157] + b[157] == out[157] is 1.000000 + 2.000000 = 3.000000
a[158] + b[158] == out[158] is 1.000000 + 2.000000 = 3.000000
a[159] + b[159] == out[159] is 1.000000 + 2.000000 = 3.000000
a[160] + b[160] == out[160] is 1.000000 + 2.000000 = 3.000000
a[161] + b[161] == out[161] is 1.000000 + 2.000000 = 3.000000
a[162] + b[162] == out[162] is 1.000000 + 2.000000 = 3.000000
a[163] + b[163] == out[163] is 1.000000 + 2.000000 = 3.000000
a[164] + b[164] == out[164] is 1.000000 + 2.000000 = 3.000000
a[165] + b[165] == out[165] is 1.000000 + 2.000000 = 3.000000
a[166] + b[166] == out[166] is 1.000000 + 2.000000 = 3.000000
a[167] + b[167] == out[167] is 1.000000 + 2.000000 = 3.000000
a[168] + b[168] == out[168] is 1.000000 + 2.000000 = 3.000000
a[169] + b[169] == out[169] is 1.000000 + 2.000000 = 3.000000
a[170] + b[170] == out[170] is 1.000000 + 2.000000 = 3.000000
a[171] + b[171] == out[171] is 1.000000 + 2.000000 = 3.000000
a[172] + b[172] == out[172] is 1.000000 + 2.000000 = 3.000000
a[173] + b[173] == out[173] is 1.000000 + 2.000000 = 3.000000
a[174] + b[174] == out[174] is 1.000000 + 2.000000 = 3.000000
a[175] + b[175] == out[175] is 1.000000 + 2.000000 = 3.000000
a[176] + b[176] == out[176] is 1.000000 + 2.000000 = 3.000000
a[177] + b[177] == out[177] is 1.000000 + 2.000000 = 3.000000
a[178] + b[178] == out[178] is 1.000000 + 2.000000 = 3.000000
a[179] + b[179] == out[179] is 1.000000 + 2.000000 = 3.000000
a[180] + b[180] == out[180] is 1.000000 + 2.000000 = 3.000000
a[181] + b[181] == out[181] is 1.000000 + 2.000000 = 3.000000
a[182] + b[182] == out[182] is 1.000000 + 2.000000 = 3.000000
a[183] + b[183] == out[183] is 1.000000 + 2.000000 = 3.000000
a[184] + b[184] == out[184] is 1.000000 + 2.000000 = 3.000000
a[185] + b[185] == out[185] is 1.000000 + 2.000000 = 3.000000
a[186] + b[186] == out[186] is 1.000000 + 2.000000 = 3.000000
a[187] + b[187] == out[187] is 1.000000 + 2.000000 = 3.000000
a[188] + b[188] == out[188] is 1.000000 + 2.000000 = 3.000000
a[189] + b[189] == out[189] is 1.000000 + 2.000000 = 3.000000
a[190] + b[190] == out[190] is 1.000000 + 2.000000 = 3.000000
a[191] + b[191] == out[191] is 1.000000 + 2.000000 = 3.000000
a[192] + b[192] == out[192] is 1.000000 + 2.000000 = 3.000000
a[193] + b[193] == out[193] is 1.000000 + 2.000000 = 3.000000
a[194] + b[194] == out[194] is 1.000000 + 2.000000 = 3.000000
a[195] + b[195] == out[195] is 1.000000 + 2.000000 = 3.000000
a[196] + b[196] == out[196] is 1.000000 + 2.000000 = 3.000000
a[197] + b[197] == out[197] is 1.000000 + 2.000000 = 3.000000
a[198] + b[198] == out[198] is 1.000000 + 2.000000 = 3.000000
a[199] + b[199] == out[199] is 1.000000 + 2.000000 = 3.000000
a[200] + b[200] == out[200] is 1.000000 + 2.000000 = 3.000000
a[201] + b[201] == out[201] is 1.000000 + 2.000000 = 3.000000
a[202] + b[202] == out[202] is 1.000000 + 2.000000 = 3.000000
a[203] + b[203] == out[203] is 1.000000 + 2.000000 = 3.000000
a[204] + b[204] == out[204] is 1.000000 + 2.000000 = 3.000000
a[205] + b[205] == out[205] is 1.000000 + 2.000000 = 3.000000
a[206] + b[206] == out[206] is 1.000000 + 2.000000 = 3.000000
a[207] + b[207] == out[207] is 1.000000 + 2.000000 = 3.000000
a[208] + b[208] == out[208] is 1.000000 + 2.000000 = 3.000000
a[209] + b[209] == out[209] is 1.000000 + 2.000000 = 3.000000
a[210] + b[210] == out[210] is 1.000000 + 2.000000 = 3.000000
a[211] + b[211] == out[211] is 1.000000 + 2.000000 = 3.000000
a[212] + b[212] == out[212] is 1.000000 + 2.000000 = 3.000000
a[213] + b[213] == out[213] is 1.000000 + 2.000000 = 3.000000
a[214] + b[214] == out[214] is 1.000000 + 2.000000 = 3.000000
a[215] + b[215] == out[215] is 1.000000 + 2.000000 = 3.000000
a[216] + b[216] == out[216] is 1.000000 + 2.000000 = 3.000000
a[217] + b[217] == out[217] is 1.000000 + 2.000000 = 3.000000
a[218] + b[218] == out[218] is 1.000000 + 2.000000 = 3.000000
a[219] + b[219] == out[219] is 1.000000 + 2.000000 = 3.000000
a[220] + b[220] == out[220] is 1.000000 + 2.000000 = 3.000000
a[221] + b[221] == out[221] is 1.000000 + 2.000000 = 3.000000
a[222] + b[222] == out[222] is 1.000000 + 2.000000 = 3.000000
a[223] + b[223] == out[223] is 1.000000 + 2.000000 = 3.000000
a[224] + b[224] == out[224] is 1.000000 + 2.000000 = 3.000000
a[225] + b[225] == out[225] is 1.000000 + 2.000000 = 3.000000
a[226] + b[226] == out[226] is 1.000000 + 2.000000 = 3.000000
a[227] + b[227] == out[227] is 1.000000 + 2.000000 = 3.000000
a[228] + b[228] == out[228] is 1.000000 + 2.000000 = 3.000000
a[229] + b[229] == out[229] is 1.000000 + 2.000000 = 3.000000
a[230] + b[230] == out[230] is 1.000000 + 2.000000 = 3.000000
a[231] + b[231] == out[231] is 1.000000 + 2.000000 = 3.000000
a[232] + b[232] == out[232] is 1.000000 + 2.000000 = 3.000000
a[233] + b[233] == out[233] is 1.000000 + 2.000000 = 3.000000
a[234] + b[234] == out[234] is 1.000000 + 2.000000 = 3.000000
a[235] + b[235] == out[235] is 1.000000 + 2.000000 = 3.000000
a[236] + b[236] == out[236] is 1.000000 + 2.000000 = 3.000000
a[237] + b[237] == out[237] is 1.000000 + 2.000000 = 3.000000
a[238] + b[238] == out[238] is 1.000000 + 2.000000 = 3.000000
a[239] + b[239] == out[239] is 1.000000 + 2.000000 = 3.000000
a[240] + b[240] == out[240] is 1.000000 + 2.000000 = 3.000000
a[241] + b[241] == out[241] is 1.000000 + 2.000000 = 3.000000
a[242] + b[242] == out[242] is 1.000000 + 2.000000 = 3.000000
a[243] + b[243] == out[243] is 1.000000 + 2.000000 = 3.000000
a[244] + b[244] == out[244] is 1.000000 + 2.000000 = 3.000000
a[245] + b[245] == out[245] is 1.000000 + 2.000000 = 3.000000
a[246] + b[246] == out[246] is 1.000000 + 2.000000 = 3.000000
a[247] + b[247] == out[247] is 1.000000 + 2.000000 = 3.000000
a[248] + b[248] == out[248] is 1.000000 + 2.000000 = 3.000000
a[249] + b[249] == out[249] is 1.000000 + 2.000000 = 3.000000
a[250] + b[250] == out[250] is 1.000000 + 2.000000 = 3.000000
a[251] + b[251] == out[251] is 1.000000 + 2.000000 = 3.000000
a[252] + b[252] == out[252] is 1.000000 + 2.000000 = 3.000000
a[253] + b[253] == out[253] is 1.000000 + 2.000000 = 3.000000
a[254] + b[254] == out[254] is 1.000000 + 2.000000 = 3.000000
a[255] + b[255] == out[255] is 1.000000 + 2.000000 = 3.000000
a[256] + b[256] == out[256] is 1.000000 + 2.000000 = 3.000000
a[257] + b[257] == out[257] is 1.000000 + 2.000000 = 3.000000
a[258] + b[258] == out[258] is 1.000000 + 2.000000 = 3.000000
a[259] + b[259] == out[259] is 1.000000 + 2.000000 = 3.000000
a[260] + b[260] == out[260] is 1.000000 + 2.000000 = 3.000000
a[261] + b[261] == out[261] is 1.000000 + 2.000000 = 3.000000
a[262] + b[262] == out[262] is 1.000000 + 2.000000 = 3.000000
a[263] + b[263] == out[263] is 1.000000 + 2.000000 = 3.000000
a[264] + b[264] == out[264] is 1.000000 + 2.000000 = 3.000000
a[265] + b[265] == out[265] is 1.000000 + 2.000000 = 3.000000
a[266] + b[266] == out[266] is 1.000000 + 2.000000 = 3.000000
a[267] + b[267] == out[267] is 1.000000 + 2.000000 = 3.000000
a[268] + b[268] == out[268] is 1.000000 + 2.000000 = 3.000000
a[269] + b[269] == out[269] is 1.000000 + 2.000000 = 3.000000
a[270] + b[270] == out[270] is 1.000000 + 2.000000 = 3.000000
a[271] + b[271] == out[271] is 1.000000 + 2.000000 = 3.000000
a[272] + b[272] == out[272] is 1.000000 + 2.000000 = 3.000000
a[273] + b[273] == out[273] is 1.000000 + 2.000000 = 3.000000
a[274] + b[274] == out[274] is 1.000000 + 2.000000 = 3.000000
a[275] + b[275] == out[275] is 1.000000 + 2.000000 = 3.000000
a[276] + b[276] == out[276] is 1.000000 + 2.000000 = 3.000000
a[277] + b[277] == out[277] is 1.000000 + 2.000000 = 3.000000
a[278] + b[278] == out[278] is 1.000000 + 2.000000 = 3.000000
a[279] + b[279] == out[279] is 1.000000 + 2.000000 = 3.000000
a[280] + b[280] == out[280] is 1.000000 + 2.000000 = 3.000000
a[281] + b[281] == out[281] is 1.000000 + 2.000000 = 3.000000
a[282] + b[282] == out[282] is 1.000000 + 2.000000 = 3.000000
a[283] + b[283] == out[283] is 1.000000 + 2.000000 = 3.000000
a[284] + b[284] == out[284] is 1.000000 + 2.000000 = 3.000000
a[285] + b[285] == out[285] is 1.000000 + 2.000000 = 3.000000
a[286] + b[286] == out[286] is 1.000000 + 2.000000 = 3.000000
a[287] + b[287] == out[287] is 1.000000 + 2.000000 = 3.000000
a[288] + b[288] == out[288] is 1.000000 + 2.000000 = 3.000000
a[289] + b[289] == out[289] is 1.000000 + 2.000000 = 3.000000
a[290] + b[290] == out[290] is 1.000000 + 2.000000 = 3.000000
a[291] + b[291] == out[291] is 1.000000 + 2.000000 = 3.000000
a[292] + b[292] == out[292] is 1.000000 + 2.000000 = 3.000000
a[293] + b[293] == out[293] is 1.000000 + 2.000000 = 3.000000
a[294] + b[294] == out[294] is 1.000000 + 2.000000 = 3.000000
a[295] + b[295] == out[295] is 1.000000 + 2.000000 = 3.000000
a[296] + b[296] == out[296] is 1.000000 + 2.000000 = 3.000000
a[297] + b[297] == out[297] is 1.000000 + 2.000000 = 3.000000
a[298] + b[298] == out[298] is 1.000000 + 2.000000 = 3.000000
a[299] + b[299] == out[299] is 1.000000 + 2.000000 = 3.000000
a[300] + b[300] == out[300] is 1.000000 + 2.000000 = 3.000000
a[301] + b[301] == out[301] is 1.000000 + 2.000000 = 3.000000
a[302] + b[302] == out[302] is 1.000000 + 2.000000 = 3.000000
a[303] + b[303] == out[303] is 1.000000 + 2.000000 = 3.000000
a[304] + b[304] == out[304] is 1.000000 + 2.000000 = 3.000000
a[305] + b[305] == out[305] is 1.000000 + 2.000000 = 3.000000
a[306] + b[306] == out[306] is 1.000000 + 2.000000 = 3.000000
a[307] + b[307] == out[307] is 1.000000 + 2.000000 = 3.000000
a[308] + b[308] == out[308] is 1.000000 + 2.000000 = 3.000000
a[309] + b[309] == out[309] is 1.000000 + 2.000000 = 3.000000
a[310] + b[310] == out[310] is 1.000000 + 2.000000 = 3.000000
a[311] + b[311] == out[311] is 1.000000 + 2.000000 = 3.000000
a[312] + b[312] == out[312] is 1.000000 + 2.000000 = 3.000000
a[313] + b[313] == out[313] is 1.000000 + 2.000000 = 3.000000
a[314] + b[314] == out[314] is 1.000000 + 2.000000 = 3.000000
a[315] + b[315] == out[315] is 1.000000 + 2.000000 = 3.000000
a[316] + b[316] == out[316] is 1.000000 + 2.000000 = 3.000000
a[317] + b[317] == out[317] is 1.000000 + 2.000000 = 3.000000
a[318] + b[318] == out[318] is 1.000000 + 2.000000 = 3.000000
a[319] + b[319] == out[319] is 1.000000 + 2.000000 = 3.000000
a[320] + b[320] == out[320] is 1.000000 + 2.000000 = 3.000000
a[321] + b[321] == out[321] is 1.000000 + 2.000000 = 3.000000
a[322] + b[322] == out[322] is 1.000000 + 2.000000 = 3.000000
a[323] + b[323] == out[323] is 1.000000 + 2.000000 = 3.000000
a[324] + b[324] == out[324] is 1.000000 + 2.000000 = 3.000000
a[325] + b[325] == out[325] is 1.000000 + 2.000000 = 3.000000
a[326] + b[326] == out[326] is 1.000000 + 2.000000 = 3.000000
a[327] + b[327] == out[327] is 1.000000 + 2.000000 = 3.000000
a[328] + b[328] == out[328] is 1.000000 + 2.000000 = 3.000000
a[329] + b[329] == out[329] is 1.000000 + 2.000000 = 3.000000
a[330] + b[330] == out[330] is 1.000000 + 2.000000 = 3.000000
a[331] + b[331] == out[331] is 1.000000 + 2.000000 = 3.000000
a[332] + b[332] == out[332] is 1.000000 + 2.000000 = 3.000000
a[333] + b[333] == out[333] is 1.000000 + 2.000000 = 3.000000
a[334] + b[334] == out[334] is 1.000000 + 2.000000 = 3.000000
a[335] + b[335] == out[335] is 1.000000 + 2.000000 = 3.000000
a[336] + b[336] == out[336] is 1.000000 + 2.000000 = 3.000000
a[337] + b[337] == out[337] is 1.000000 + 2.000000 = 3.000000
a[338] + b[338] == out[338] is 1.000000 + 2.000000 = 3.000000
a[339] + b[339] == out[339] is 1.000000 + 2.000000 = 3.000000
a[340] + b[340] == out[340] is 1.000000 + 2.000000 = 3.000000
a[341] + b[341] == out[341] is 1.000000 + 2.000000 = 3.000000
a[342] + b[342] == out[342] is 1.000000 + 2.000000 = 3.000000
a[343] + b[343] == out[343] is 1.000000 + 2.000000 = 3.000000
a[344] + b[344] == out[344] is 1.000000 + 2.000000 = 3.000000
a[345] + b[345] == out[345] is 1.000000 + 2.000000 = 3.000000
a[346] + b[346] == out[346] is 1.000000 + 2.000000 = 3.000000
a[347] + b[347] == out[347] is 1.000000 + 2.000000 = 3.000000
a[348] + b[348] == out[348] is 1.000000 + 2.000000 = 3.000000
a[349] + b[349] == out[349] is 1.000000 + 2.000000 = 3.000000
a[350] + b[350] == out[350] is 1.000000 + 2.000000 = 3.000000
a[351] + b[351] == out[351] is 1.000000 + 2.000000 = 3.000000
a[352] + b[352] == out[352] is 1.000000 + 2.000000 = 3.000000
a[353] + b[353] == out[353] is 1.000000 + 2.000000 = 3.000000
a[354] + b[354] == out[354] is 1.000000 + 2.000000 = 3.000000
a[355] + b[355] == out[355] is 1.000000 + 2.000000 = 3.000000
a[356] + b[356] == out[356] is 1.000000 + 2.000000 = 3.000000
a[357] + b[357] == out[357] is 1.000000 + 2.000000 = 3.000000
a[358] + b[358] == out[358] is 1.000000 + 2.000000 = 3.000000
a[359] + b[359] == out[359] is 1.000000 + 2.000000 = 3.000000
a[360] + b[360] == out[360] is 1.000000 + 2.000000 = 3.000000
a[361] + b[361] == out[361] is 1.000000 + 2.000000 = 3.000000
a[362] + b[362] == out[362] is 1.000000 + 2.000000 = 3.000000
a[363] + b[363] == out[363] is 1.000000 + 2.000000 = 3.000000
a[364] + b[364] == out[364] is 1.000000 + 2.000000 = 3.000000
a[365] + b[365] == out[365] is 1.000000 + 2.000000 = 3.000000
a[366] + b[366] == out[366] is 1.000000 + 2.000000 = 3.000000
a[367] + b[367] == out[367] is 1.000000 + 2.000000 = 3.000000
a[368] + b[368] == out[368] is 1.000000 + 2.000000 = 3.000000
a[369] + b[369] == out[369] is 1.000000 + 2.000000 = 3.000000
a[370] + b[370] == out[370] is 1.000000 + 2.000000 = 3.000000
a[371] + b[371] == out[371] is 1.000000 + 2.000000 = 3.000000
a[372] + b[372] == out[372] is 1.000000 + 2.000000 = 3.000000
a[373] + b[373] == out[373] is 1.000000 + 2.000000 = 3.000000
a[374] + b[374] == out[374] is 1.000000 + 2.000000 = 3.000000
a[375] + b[375] == out[375] is 1.000000 + 2.000000 = 3.000000
a[376] + b[376] == out[376] is 1.000000 + 2.000000 = 3.000000
a[377] + b[377] == out[377] is 1.000000 + 2.000000 = 3.000000
a[378] + b[378] == out[378] is 1.000000 + 2.000000 = 3.000000
a[379] + b[379] == out[379] is 1.000000 + 2.000000 = 3.000000
a[380] + b[380] == out[380] is 1.000000 + 2.000000 = 3.000000
a[381] + b[381] == out[381] is 1.000000 + 2.000000 = 3.000000
a[382] + b[382] == out[382] is 1.000000 + 2.000000 = 3.000000
a[383] + b[383] == out[383] is 1.000000 + 2.000000 = 3.000000
a[384] + b[384] == out[384] is 1.000000 + 2.000000 = 3.000000
a[385] + b[385] == out[385] is 1.000000 + 2.000000 = 3.000000
a[386] + b[386] == out[386] is 1.000000 + 2.000000 = 3.000000
a[387] + b[387] == out[387] is 1.000000 + 2.000000 = 3.000000
a[388] + b[388] == out[388] is 1.000000 + 2.000000 = 3.000000
a[389] + b[389] == out[389] is 1.000000 + 2.000000 = 3.000000
a[390] + b[390] == out[390] is 1.000000 + 2.000000 = 3.000000
a[391] + b[391] == out[391] is 1.000000 + 2.000000 = 3.000000
a[392] + b[392] == out[392] is 1.000000 + 2.000000 = 3.000000
a[393] + b[393] == out[393] is 1.000000 + 2.000000 = 3.000000
a[394] + b[394] == out[394] is 1.000000 + 2.000000 = 3.000000
a[395] + b[395] == out[395] is 1.000000 + 2.000000 = 3.000000
a[396] + b[396] == out[396] is 1.000000 + 2.000000 = 3.000000
a[397] + b[397] == out[397] is 1.000000 + 2.000000 = 3.000000
a[398] + b[398] == out[398] is 1.000000 + 2.000000 = 3.000000
a[399] + b[399] == out[399] is 1.000000 + 2.000000 = 3.000000
a[400] + b[400] == out[400] is 1.000000 + 2.000000 = 3.000000
a[401] + b[401] == out[401] is 1.000000 + 2.000000 = 3.000000
a[402] + b[402] == out[402] is 1.000000 + 2.000000 = 3.000000
a[403] + b[403] == out[403] is 1.000000 + 2.000000 = 3.000000
a[404] + b[404] == out[404] is 1.000000 + 2.000000 = 3.000000
a[405] + b[405] == out[405] is 1.000000 + 2.000000 = 3.000000
a[406] + b[406] == out[406] is 1.000000 + 2.000000 = 3.000000
a[407] + b[407] == out[407] is 1.000000 + 2.000000 = 3.000000
a[408] + b[408] == out[408] is 1.000000 + 2.000000 = 3.000000
a[409] + b[409] == out[409] is 1.000000 + 2.000000 = 3.000000
a[410] + b[410] == out[410] is 1.000000 + 2.000000 = 3.000000
a[411] + b[411] == out[411] is 1.000000 + 2.000000 = 3.000000
a[412] + b[412] == out[412] is 1.000000 + 2.000000 = 3.000000
a[413] + b[413] == out[413] is 1.000000 + 2.000000 = 3.000000
a[414] + b[414] == out[414] is 1.000000 + 2.000000 = 3.000000
a[415] + b[415] == out[415] is 1.000000 + 2.000000 = 3.000000
a[416] + b[416] == out[416] is 1.000000 + 2.000000 = 3.000000
a[417] + b[417] == out[417] is 1.000000 + 2.000000 = 3.000000
a[418] + b[418] == out[418] is 1.000000 + 2.000000 = 3.000000
a[419] + b[419] == out[419] is 1.000000 + 2.000000 = 3.000000
a[420] + b[420] == out[420] is 1.000000 + 2.000000 = 3.000000
a[421] + b[421] == out[421] is 1.000000 + 2.000000 = 3.000000
a[422] + b[422] == out[422] is 1.000000 + 2.000000 = 3.000000
a[423] + b[423] == out[423] is 1.000000 + 2.000000 = 3.000000
a[424] + b[424] == out[424] is 1.000000 + 2.000000 = 3.000000
a[425] + b[425] == out[425] is 1.000000 + 2.000000 = 3.000000
a[426] + b[426] == out[426] is 1.000000 + 2.000000 = 3.000000
a[427] + b[427] == out[427] is 1.000000 + 2.000000 = 3.000000
a[428] + b[428] == out[428] is 1.000000 + 2.000000 = 3.000000
a[429] + b[429] == out[429] is 1.000000 + 2.000000 = 3.000000
a[430] + b[430] == out[430] is 1.000000 + 2.000000 = 3.000000
a[431] + b[431] == out[431] is 1.000000 + 2.000000 = 3.000000
a[432] + b[432] == out[432] is 1.000000 + 2.000000 = 3.000000
a[433] + b[433] == out[433] is 1.000000 + 2.000000 = 3.000000
a[434] + b[434] == out[434] is 1.000000 + 2.000000 = 3.000000
a[435] + b[435] == out[435] is 1.000000 + 2.000000 = 3.000000
a[436] + b[436] == out[436] is 1.000000 + 2.000000 = 3.000000
a[437] + b[437] == out[437] is 1.000000 + 2.000000 = 3.000000
a[438] + b[438] == out[438] is 1.000000 + 2.000000 = 3.000000
a[439] + b[439] == out[439] is 1.000000 + 2.000000 = 3.000000
a[440] + b[440] == out[440] is 1.000000 + 2.000000 = 3.000000
a[441] + b[441] == out[441] is 1.000000 + 2.000000 = 3.000000
a[442] + b[442] == out[442] is 1.000000 + 2.000000 = 3.000000
a[443] + b[443] == out[443] is 1.000000 + 2.000000 = 3.000000
a[444] + b[444] == out[444] is 1.000000 + 2.000000 = 3.000000
a[445] + b[445] == out[445] is 1.000000 + 2.000000 = 3.000000
a[446] + b[446] == out[446] is 1.000000 + 2.000000 = 3.000000
a[447] + b[447] == out[447] is 1.000000 + 2.000000 = 3.000000
a[448] + b[448] == out[448] is 1.000000 + 2.000000 = 3.000000
a[449] + b[449] == out[449] is 1.000000 + 2.000000 = 3.000000
a[450] + b[450] == out[450] is 1.000000 + 2.000000 = 3.000000
a[451] + b[451] == out[451] is 1.000000 + 2.000000 = 3.000000
a[452] + b[452] == out[452] is 1.000000 + 2.000000 = 3.000000
a[453] + b[453] == out[453] is 1.000000 + 2.000000 = 3.000000
a[454] + b[454] == out[454] is 1.000000 + 2.000000 = 3.000000
a[455] + b[455] == out[455] is 1.000000 + 2.000000 = 3.000000
a[456] + b[456] == out[456] is 1.000000 + 2.000000 = 3.000000
a[457] + b[457] == out[457] is 1.000000 + 2.000000 = 3.000000
a[458] + b[458] == out[458] is 1.000000 + 2.000000 = 3.000000
a[459] + b[459] == out[459] is 1.000000 + 2.000000 = 3.000000
a[460] + b[460] == out[460] is 1.000000 + 2.000000 = 3.000000
a[461] + b[461] == out[461] is 1.000000 + 2.000000 = 3.000000
a[462] + b[462] == out[462] is 1.000000 + 2.000000 = 3.000000
a[463] + b[463] == out[463] is 1.000000 + 2.000000 = 3.000000
a[464] + b[464] == out[464] is 1.000000 + 2.000000 = 3.000000
a[465] + b[465] == out[465] is 1.000000 + 2.000000 = 3.000000
a[466] + b[466] == out[466] is 1.000000 + 2.000000 = 3.000000
a[467] + b[467] == out[467] is 1.000000 + 2.000000 = 3.000000
a[468] + b[468] == out[468] is 1.000000 + 2.000000 = 3.000000
a[469] + b[469] == out[469] is 1.000000 + 2.000000 = 3.000000
a[470] + b[470] == out[470] is 1.000000 + 2.000000 = 3.000000
a[471] + b[471] == out[471] is 1.000000 + 2.000000 = 3.000000
a[472] + b[472] == out[472] is 1.000000 + 2.000000 = 3.000000
a[473] + b[473] == out[473] is 1.000000 + 2.000000 = 3.000000
a[474] + b[474] == out[474] is 1.000000 + 2.000000 = 3.000000
a[475] + b[475] == out[475] is 1.000000 + 2.000000 = 3.000000
a[476] + b[476] == out[476] is 1.000000 + 2.000000 = 3.000000
a[477] + b[477] == out[477] is 1.000000 + 2.000000 = 3.000000
a[478] + b[478] == out[478] is 1.000000 + 2.000000 = 3.000000
a[479] + b[479] == out[479] is 1.000000 + 2.000000 = 3.000000
a[480] + b[480] == out[480] is 1.000000 + 2.000000 = 3.000000
a[481] + b[481] == out[481] is 1.000000 + 2.000000 = 3.000000
a[482] + b[482] == out[482] is 1.000000 + 2.000000 = 3.000000
a[483] + b[483] == out[483] is 1.000000 + 2.000000 = 3.000000
a[484] + b[484] == out[484] is 1.000000 + 2.000000 = 3.000000
a[485] + b[485] == out[485] is 1.000000 + 2.000000 = 3.000000
a[486] + b[486] == out[486] is 1.000000 + 2.000000 = 3.000000
a[487] + b[487] == out[487] is 1.000000 + 2.000000 = 3.000000
a[488] + b[488] == out[488] is 1.000000 + 2.000000 = 3.000000
a[489] + b[489] == out[489] is 1.000000 + 2.000000 = 3.000000
a[490] + b[490] == out[490] is 1.000000 + 2.000000 = 3.000000
a[491] + b[491] == out[491] is 1.000000 + 2.000000 = 3.000000
a[492] + b[492] == out[492] is 1.000000 + 2.000000 = 3.000000
a[493] + b[493] == out[493] is 1.000000 + 2.000000 = 3.000000
a[494] + b[494] == out[494] is 1.000000 + 2.000000 = 3.000000
a[495] + b[495] == out[495] is 1.000000 + 2.000000 = 3.000000
a[496] + b[496] == out[496] is 1.000000 + 2.000000 = 3.000000
a[497] + b[497] == out[497] is 1.000000 + 2.000000 = 3.000000
a[498] + b[498] == out[498] is 1.000000 + 2.000000 = 3.000000
a[499] + b[499] == out[499] is 1.000000 + 2.000000 = 3.000000
a[500] + b[500] == out[500] is 1.000000 + 2.000000 = 3.000000
a[501] + b[501] == out[501] is 1.000000 + 2.000000 = 3.000000
a[502] + b[502] == out[502] is 1.000000 + 2.000000 = 3.000000
a[503] + b[503] == out[503] is 1.000000 + 2.000000 = 3.000000
a[504] + b[504] == out[504] is 1.000000 + 2.000000 = 3.000000
a[505] + b[505] == out[505] is 1.000000 + 2.000000 = 3.000000
a[506] + b[506] == out[506] is 1.000000 + 2.000000 = 3.000000
a[507] + b[507] == out[507] is 1.000000 + 2.000000 = 3.000000
a[508] + b[508] == out[508] is 1.000000 + 2.000000 = 3.000000
a[509] + b[509] == out[509] is 1.000000 + 2.000000 = 3.000000
a[510] + b[510] == out[510] is 1.000000 + 2.000000 = 3.000000
a[511] + b[511] == out[511] is 1.000000 + 2.000000 = 3.000000
a[512] + b[512] == out[512] is 1.000000 + 2.000000 = 3.000000
a[513] + b[513] == out[513] is 1.000000 + 2.000000 = 3.000000
a[514] + b[514] == out[514] is 1.000000 + 2.000000 = 3.000000
a[515] + b[515] == out[515] is 1.000000 + 2.000000 = 3.000000
a[516] + b[516] == out[516] is 1.000000 + 2.000000 = 3.000000
a[517] + b[517] == out[517] is 1.000000 + 2.000000 = 3.000000
a[518] + b[518] == out[518] is 1.000000 + 2.000000 = 3.000000
a[519] + b[519] == out[519] is 1.000000 + 2.000000 = 3.000000
a[520] + b[520] == out[520] is 1.000000 + 2.000000 = 3.000000
a[521] + b[521] == out[521] is 1.000000 + 2.000000 = 3.000000
a[522] + b[522] == out[522] is 1.000000 + 2.000000 = 3.000000
a[523] + b[523] == out[523] is 1.000000 + 2.000000 = 3.000000
a[524] + b[524] == out[524] is 1.000000 + 2.000000 = 3.000000
a[525] + b[525] == out[525] is 1.000000 + 2.000000 = 3.000000
a[526] + b[526] == out[526] is 1.000000 + 2.000000 = 3.000000
a[527] + b[527] == out[527] is 1.000000 + 2.000000 = 3.000000
a[528] + b[528] == out[528] is 1.000000 + 2.000000 = 3.000000
a[529] + b[529] == out[529] is 1.000000 + 2.000000 = 3.000000
a[530] + b[530] == out[530] is 1.000000 + 2.000000 = 3.000000
a[531] + b[531] == out[531] is 1.000000 + 2.000000 = 3.000000
a[532] + b[532] == out[532] is 1.000000 + 2.000000 = 3.000000
a[533] + b[533] == out[533] is 1.000000 + 2.000000 = 3.000000
a[534] + b[534] == out[534] is 1.000000 + 2.000000 = 3.000000
a[535] + b[535] == out[535] is 1.000000 + 2.000000 = 3.000000
a[536] + b[536] == out[536] is 1.000000 + 2.000000 = 3.000000
a[537] + b[537] == out[537] is 1.000000 + 2.000000 = 3.000000
a[538] + b[538] == out[538] is 1.000000 + 2.000000 = 3.000000
a[539] + b[539] == out[539] is 1.000000 + 2.000000 = 3.000000
a[540] + b[540] == out[540] is 1.000000 + 2.000000 = 3.000000
a[541] + b[541] == out[541] is 1.000000 + 2.000000 = 3.000000
a[542] + b[542] == out[542] is 1.000000 + 2.000000 = 3.000000
a[543] + b[543] == out[543] is 1.000000 + 2.000000 = 3.000000
a[544] + b[544] == out[544] is 1.000000 + 2.000000 = 3.000000
a[545] + b[545] == out[545] is 1.000000 + 2.000000 = 3.000000
a[546] + b[546] == out[546] is 1.000000 + 2.000000 = 3.000000
a[547] + b[547] == out[547] is 1.000000 + 2.000000 = 3.000000
a[548] + b[548] == out[548] is 1.000000 + 2.000000 = 3.000000
a[549] + b[549] == out[549] is 1.000000 + 2.000000 = 3.000000
a[550] + b[550] == out[550] is 1.000000 + 2.000000 = 3.000000
a[551] + b[551] == out[551] is 1.000000 + 2.000000 = 3.000000
a[552] + b[552] == out[552] is 1.000000 + 2.000000 = 3.000000
a[553] + b[553] == out[553] is 1.000000 + 2.000000 = 3.000000
a[554] + b[554] == out[554] is 1.000000 + 2.000000 = 3.000000
a[555] + b[555] == out[555] is 1.000000 + 2.000000 = 3.000000
a[556] + b[556] == out[556] is 1.000000 + 2.000000 = 3.000000
a[557] + b[557] == out[557] is 1.000000 + 2.000000 = 3.000000
a[558] + b[558] == out[558] is 1.000000 + 2.000000 = 3.000000
a[559] + b[559] == out[559] is 1.000000 + 2.000000 = 3.000000
a[560] + b[560] == out[560] is 1.000000 + 2.000000 = 3.000000
a[561] + b[561] == out[561] is 1.000000 + 2.000000 = 3.000000
a[562] + b[562] == out[562] is 1.000000 + 2.000000 = 3.000000
a[563] + b[563] == out[563] is 1.000000 + 2.000000 = 3.000000
a[564] + b[564] == out[564] is 1.000000 + 2.000000 = 3.000000
a[565] + b[565] == out[565] is 1.000000 + 2.000000 = 3.000000
a[566] + b[566] == out[566] is 1.000000 + 2.000000 = 3.000000
a[567] + b[567] == out[567] is 1.000000 + 2.000000 = 3.000000
a[568] + b[568] == out[568] is 1.000000 + 2.000000 = 3.000000
a[569] + b[569] == out[569] is 1.000000 + 2.000000 = 3.000000
a[570] + b[570] == out[570] is 1.000000 + 2.000000 = 3.000000
a[571] + b[571] == out[571] is 1.000000 + 2.000000 = 3.000000
a[572] + b[572] == out[572] is 1.000000 + 2.000000 = 3.000000
a[573] + b[573] == out[573] is 1.000000 + 2.000000 = 3.000000
a[574] + b[574] == out[574] is 1.000000 + 2.000000 = 3.000000
a[575] + b[575] == out[575] is 1.000000 + 2.000000 = 3.000000
a[576] + b[576] == out[576] is 1.000000 + 2.000000 = 3.000000
a[577] + b[577] == out[577] is 1.000000 + 2.000000 = 3.000000
a[578] + b[578] == out[578] is 1.000000 + 2.000000 = 3.000000
a[579] + b[579] == out[579] is 1.000000 + 2.000000 = 3.000000
a[580] + b[580] == out[580] is 1.000000 + 2.000000 = 3.000000
a[581] + b[581] == out[581] is 1.000000 + 2.000000 = 3.000000
a[582] + b[582] == out[582] is 1.000000 + 2.000000 = 3.000000
a[583] + b[583] == out[583] is 1.000000 + 2.000000 = 3.000000
a[584] + b[584] == out[584] is 1.000000 + 2.000000 = 3.000000
a[585] + b[585] == out[585] is 1.000000 + 2.000000 = 3.000000
a[586] + b[586] == out[586] is 1.000000 + 2.000000 = 3.000000
a[587] + b[587] == out[587] is 1.000000 + 2.000000 = 3.000000
a[588] + b[588] == out[588] is 1.000000 + 2.000000 = 3.000000
a[589] + b[589] == out[589] is 1.000000 + 2.000000 = 3.000000
a[590] + b[590] == out[590] is 1.000000 + 2.000000 = 3.000000
a[591] + b[591] == out[591] is 1.000000 + 2.000000 = 3.000000
a[592] + b[592] == out[592] is 1.000000 + 2.000000 = 3.000000
a[593] + b[593] == out[593] is 1.000000 + 2.000000 = 3.000000
a[594] + b[594] == out[594] is 1.000000 + 2.000000 = 3.000000
a[595] + b[595] == out[595] is 1.000000 + 2.000000 = 3.000000
a[596] + b[596] == out[596] is 1.000000 + 2.000000 = 3.000000
a[597] + b[597] == out[597] is 1.000000 + 2.000000 = 3.000000
a[598] + b[598] == out[598] is 1.000000 + 2.000000 = 3.000000
a[599] + b[599] == out[599] is 1.000000 + 2.000000 = 3.000000
a[600] + b[600] == out[600] is 1.000000 + 2.000000 = 3.000000
a[601] + b[601] == out[601] is 1.000000 + 2.000000 = 3.000000
a[602] + b[602] == out[602] is 1.000000 + 2.000000 = 3.000000
a[603] + b[603] == out[603] is 1.000000 + 2.000000 = 3.000000
a[604] + b[604] == out[604] is 1.000000 + 2.000000 = 3.000000
a[605] + b[605] == out[605] is 1.000000 + 2.000000 = 3.000000
a[606] + b[606] == out[606] is 1.000000 + 2.000000 = 3.000000
a[607] + b[607] == out[607] is 1.000000 + 2.000000 = 3.000000
a[608] + b[608] == out[608] is 1.000000 + 2.000000 = 3.000000
a[609] + b[609] == out[609] is 1.000000 + 2.000000 = 3.000000
a[610] + b[610] == out[610] is 1.000000 + 2.000000 = 3.000000
a[611] + b[611] == out[611] is 1.000000 + 2.000000 = 3.000000
a[612] + b[612] == out[612] is 1.000000 + 2.000000 = 3.000000
a[613] + b[613] == out[613] is 1.000000 + 2.000000 = 3.000000
a[614] + b[614] == out[614] is 1.000000 + 2.000000 = 3.000000
a[615] + b[615] == out[615] is 1.000000 + 2.000000 = 3.000000
a[616] + b[616] == out[616] is 1.000000 + 2.000000 = 3.000000
a[617] + b[617] == out[617] is 1.000000 + 2.000000 = 3.000000
a[618] + b[618] == out[618] is 1.000000 + 2.000000 = 3.000000
a[619] + b[619] == out[619] is 1.000000 + 2.000000 = 3.000000
a[620] + b[620] == out[620] is 1.000000 + 2.000000 = 3.000000
a[621] + b[621] == out[621] is 1.000000 + 2.000000 = 3.000000
a[622] + b[622] == out[622] is 1.000000 + 2.000000 = 3.000000
a[623] + b[623] == out[623] is 1.000000 + 2.000000 = 3.000000
a[624] + b[624] == out[624] is 1.000000 + 2.000000 = 3.000000
a[625] + b[625] == out[625] is 1.000000 + 2.000000 = 3.000000
a[626] + b[626] == out[626] is 1.000000 + 2.000000 = 3.000000
a[627] + b[627] == out[627] is 1.000000 + 2.000000 = 3.000000
a[628] + b[628] == out[628] is 1.000000 + 2.000000 = 3.000000
a[629] + b[629] == out[629] is 1.000000 + 2.000000 = 3.000000
a[630] + b[630] == out[630] is 1.000000 + 2.000000 = 3.000000
a[631] + b[631] == out[631] is 1.000000 + 2.000000 = 3.000000
a[632] + b[632] == out[632] is 1.000000 + 2.000000 = 3.000000
a[633] + b[633] == out[633] is 1.000000 + 2.000000 = 3.000000
a[634] + b[634] == out[634] is 1.000000 + 2.000000 = 3.000000
a[635] + b[635] == out[635] is 1.000000 + 2.000000 = 3.000000
a[636] + b[636] == out[636] is 1.000000 + 2.000000 = 3.000000
a[637] + b[637] == out[637] is 1.000000 + 2.000000 = 3.000000
a[638] + b[638] == out[638] is 1.000000 + 2.000000 = 3.000000
a[639] + b[639] == out[639] is 1.000000 + 2.000000 = 3.000000
a[640] + b[640] == out[640] is 1.000000 + 2.000000 = 3.000000
a[641] + b[641] == out[641] is 1.000000 + 2.000000 = 3.000000
a[642] + b[642] == out[642] is 1.000000 + 2.000000 = 3.000000
a[643] + b[643] == out[643] is 1.000000 + 2.000000 = 3.000000
a[644] + b[644] == out[644] is 1.000000 + 2.000000 = 3.000000
a[645] + b[645] == out[645] is 1.000000 + 2.000000 = 3.000000
a[646] + b[646] == out[646] is 1.000000 + 2.000000 = 3.000000
a[647] + b[647] == out[647] is 1.000000 + 2.000000 = 3.000000
a[648] + b[648] == out[648] is 1.000000 + 2.000000 = 3.000000
a[649] + b[649] == out[649] is 1.000000 + 2.000000 = 3.000000
a[650] + b[650] == out[650] is 1.000000 + 2.000000 = 3.000000
a[651] + b[651] == out[651] is 1.000000 + 2.000000 = 3.000000
a[652] + b[652] == out[652] is 1.000000 + 2.000000 = 3.000000
a[653] + b[653] == out[653] is 1.000000 + 2.000000 = 3.000000
a[654] + b[654] == out[654] is 1.000000 + 2.000000 = 3.000000
a[655] + b[655] == out[655] is 1.000000 + 2.000000 = 3.000000
a[656] + b[656] == out[656] is 1.000000 + 2.000000 = 3.000000
a[657] + b[657] == out[657] is 1.000000 + 2.000000 = 3.000000
a[658] + b[658] == out[658] is 1.000000 + 2.000000 = 3.000000
a[659] + b[659] == out[659] is 1.000000 + 2.000000 = 3.000000
a[660] + b[660] == out[660] is 1.000000 + 2.000000 = 3.000000
a[661] + b[661] == out[661] is 1.000000 + 2.000000 = 3.000000
a[662] + b[662] == out[662] is 1.000000 + 2.000000 = 3.000000
a[663] + b[663] == out[663] is 1.000000 + 2.000000 = 3.000000
a[664] + b[664] == out[664] is 1.000000 + 2.000000 = 3.000000
a[665] + b[665] == out[665] is 1.000000 + 2.000000 = 3.000000
a[666] + b[666] == out[666] is 1.000000 + 2.000000 = 3.000000
a[667] + b[667] == out[667] is 1.000000 + 2.000000 = 3.000000
a[668] + b[668] == out[668] is 1.000000 + 2.000000 = 3.000000
a[669] + b[669] == out[669] is 1.000000 + 2.000000 = 3.000000
a[670] + b[670] == out[670] is 1.000000 + 2.000000 = 3.000000
a[671] + b[671] == out[671] is 1.000000 + 2.000000 = 3.000000
a[672] + b[672] == out[672] is 1.000000 + 2.000000 = 3.000000
a[673] + b[673] == out[673] is 1.000000 + 2.000000 = 3.000000
a[674] + b[674] == out[674] is 1.000000 + 2.000000 = 3.000000
a[675] + b[675] == out[675] is 1.000000 + 2.000000 = 3.000000
a[676] + b[676] == out[676] is 1.000000 + 2.000000 = 3.000000
a[677] + b[677] == out[677] is 1.000000 + 2.000000 = 3.000000
a[678] + b[678] == out[678] is 1.000000 + 2.000000 = 3.000000
a[679] + b[679] == out[679] is 1.000000 + 2.000000 = 3.000000
a[680] + b[680] == out[680] is 1.000000 + 2.000000 = 3.000000
a[681] + b[681] == out[681] is 1.000000 + 2.000000 = 3.000000
a[682] + b[682] == out[682] is 1.000000 + 2.000000 = 3.000000
a[683] + b[683] == out[683] is 1.000000 + 2.000000 = 3.000000
a[684] + b[684] == out[684] is 1.000000 + 2.000000 = 3.000000
a[685] + b[685] == out[685] is 1.000000 + 2.000000 = 3.000000
a[686] + b[686] == out[686] is 1.000000 + 2.000000 = 3.000000
a[687] + b[687] == out[687] is 1.000000 + 2.000000 = 3.000000
a[688] + b[688] == out[688] is 1.000000 + 2.000000 = 3.000000
a[689] + b[689] == out[689] is 1.000000 + 2.000000 = 3.000000
a[690] + b[690] == out[690] is 1.000000 + 2.000000 = 3.000000
a[691] + b[691] == out[691] is 1.000000 + 2.000000 = 3.000000
a[692] + b[692] == out[692] is 1.000000 + 2.000000 = 3.000000
a[693] + b[693] == out[693] is 1.000000 + 2.000000 = 3.000000
a[694] + b[694] == out[694] is 1.000000 + 2.000000 = 3.000000
a[695] + b[695] == out[695] is 1.000000 + 2.000000 = 3.000000
a[696] + b[696] == out[696] is 1.000000 + 2.000000 = 3.000000
a[697] + b[697] == out[697] is 1.000000 + 2.000000 = 3.000000
a[698] + b[698] == out[698] is 1.000000 + 2.000000 = 3.000000
a[699] + b[699] == out[699] is 1.000000 + 2.000000 = 3.000000
a[700] + b[700] == out[700] is 1.000000 + 2.000000 = 3.000000
a[701] + b[701] == out[701] is 1.000000 + 2.000000 = 3.000000
a[702] + b[702] == out[702] is 1.000000 + 2.000000 = 3.000000
a[703] + b[703] == out[703] is 1.000000 + 2.000000 = 3.000000
a[704] + b[704] == out[704] is 1.000000 + 2.000000 = 3.000000
a[705] + b[705] == out[705] is 1.000000 + 2.000000 = 3.000000
a[706] + b[706] == out[706] is 1.000000 + 2.000000 = 3.000000
a[707] + b[707] == out[707] is 1.000000 + 2.000000 = 3.000000
a[708] + b[708] == out[708] is 1.000000 + 2.000000 = 3.000000
a[709] + b[709] == out[709] is 1.000000 + 2.000000 = 3.000000
a[710] + b[710] == out[710] is 1.000000 + 2.000000 = 3.000000
a[711] + b[711] == out[711] is 1.000000 + 2.000000 = 3.000000
a[712] + b[712] == out[712] is 1.000000 + 2.000000 = 3.000000
a[713] + b[713] == out[713] is 1.000000 + 2.000000 = 3.000000
a[714] + b[714] == out[714] is 1.000000 + 2.000000 = 3.000000
a[715] + b[715] == out[715] is 1.000000 + 2.000000 = 3.000000
a[716] + b[716] == out[716] is 1.000000 + 2.000000 = 3.000000
a[717] + b[717] == out[717] is 1.000000 + 2.000000 = 3.000000
a[718] + b[718] == out[718] is 1.000000 + 2.000000 = 3.000000
a[719] + b[719] == out[719] is 1.000000 + 2.000000 = 3.000000
a[720] + b[720] == out[720] is 1.000000 + 2.000000 = 3.000000
a[721] + b[721] == out[721] is 1.000000 + 2.000000 = 3.000000
a[722] + b[722] == out[722] is 1.000000 + 2.000000 = 3.000000
a[723] + b[723] == out[723] is 1.000000 + 2.000000 = 3.000000
a[724] + b[724] == out[724] is 1.000000 + 2.000000 = 3.000000
a[725] + b[725] == out[725] is 1.000000 + 2.000000 = 3.000000
a[726] + b[726] == out[726] is 1.000000 + 2.000000 = 3.000000
a[727] + b[727] == out[727] is 1.000000 + 2.000000 = 3.000000
a[728] + b[728] == out[728] is 1.000000 + 2.000000 = 3.000000
a[729] + b[729] == out[729] is 1.000000 + 2.000000 = 3.000000
a[730] + b[730] == out[730] is 1.000000 + 2.000000 = 3.000000
a[731] + b[731] == out[731] is 1.000000 + 2.000000 = 3.000000
a[732] + b[732] == out[732] is 1.000000 + 2.000000 = 3.000000
a[733] + b[733] == out[733] is 1.000000 + 2.000000 = 3.000000
a[734] + b[734] == out[734] is 1.000000 + 2.000000 = 3.000000
a[735] + b[735] == out[735] is 1.000000 + 2.000000 = 3.000000
a[736] + b[736] == out[736] is 1.000000 + 2.000000 = 3.000000
a[737] + b[737] == out[737] is 1.000000 + 2.000000 = 3.000000
a[738] + b[738] == out[738] is 1.000000 + 2.000000 = 3.000000
a[739] + b[739] == out[739] is 1.000000 + 2.000000 = 3.000000
a[740] + b[740] == out[740] is 1.000000 + 2.000000 = 3.000000
a[741] + b[741] == out[741] is 1.000000 + 2.000000 = 3.000000
a[742] + b[742] == out[742] is 1.000000 + 2.000000 = 3.000000
a[743] + b[743] == out[743] is 1.000000 + 2.000000 = 3.000000
a[744] + b[744] == out[744] is 1.000000 + 2.000000 = 3.000000
a[745] + b[745] == out[745] is 1.000000 + 2.000000 = 3.000000
a[746] + b[746] == out[746] is 1.000000 + 2.000000 = 3.000000
a[747] + b[747] == out[747] is 1.000000 + 2.000000 = 3.000000
a[748] + b[748] == out[748] is 1.000000 + 2.000000 = 3.000000
a[749] + b[749] == out[749] is 1.000000 + 2.000000 = 3.000000
a[750] + b[750] == out[750] is 1.000000 + 2.000000 = 3.000000
a[751] + b[751] == out[751] is 1.000000 + 2.000000 = 3.000000
a[752] + b[752] == out[752] is 1.000000 + 2.000000 = 3.000000
a[753] + b[753] == out[753] is 1.000000 + 2.000000 = 3.000000
a[754] + b[754] == out[754] is 1.000000 + 2.000000 = 3.000000
a[755] + b[755] == out[755] is 1.000000 + 2.000000 = 3.000000
a[756] + b[756] == out[756] is 1.000000 + 2.000000 = 3.000000
a[757] + b[757] == out[757] is 1.000000 + 2.000000 = 3.000000
a[758] + b[758] == out[758] is 1.000000 + 2.000000 = 3.000000
a[759] + b[759] == out[759] is 1.000000 + 2.000000 = 3.000000
a[760] + b[760] == out[760] is 1.000000 + 2.000000 = 3.000000
a[761] + b[761] == out[761] is 1.000000 + 2.000000 = 3.000000
a[762] + b[762] == out[762] is 1.000000 + 2.000000 = 3.000000
a[763] + b[763] == out[763] is 1.000000 + 2.000000 = 3.000000
a[764] + b[764] == out[764] is 1.000000 + 2.000000 = 3.000000
a[765] + b[765] == out[765] is 1.000000 + 2.000000 = 3.000000
a[766] + b[766] == out[766] is 1.000000 + 2.000000 = 3.000000
a[767] + b[767] == out[767] is 1.000000 + 2.000000 = 3.000000
a[768] + b[768] == out[768] is 1.000000 + 2.000000 = 3.000000
a[769] + b[769] == out[769] is 1.000000 + 2.000000 = 3.000000
a[770] + b[770] == out[770] is 1.000000 + 2.000000 = 3.000000
a[771] + b[771] == out[771] is 1.000000 + 2.000000 = 3.000000
a[772] + b[772] == out[772] is 1.000000 + 2.000000 = 3.000000
a[773] + b[773] == out[773] is 1.000000 + 2.000000 = 3.000000
a[774] + b[774] == out[774] is 1.000000 + 2.000000 = 3.000000
a[775] + b[775] == out[775] is 1.000000 + 2.000000 = 3.000000
a[776] + b[776] == out[776] is 1.000000 + 2.000000 = 3.000000
a[777] + b[777] == out[777] is 1.000000 + 2.000000 = 3.000000
a[778] + b[778] == out[778] is 1.000000 + 2.000000 = 3.000000
a[779] + b[779] == out[779] is 1.000000 + 2.000000 = 3.000000
a[780] + b[780] == out[780] is 1.000000 + 2.000000 = 3.000000
a[781] + b[781] == out[781] is 1.000000 + 2.000000 = 3.000000
a[782] + b[782] == out[782] is 1.000000 + 2.000000 = 3.000000
a[783] + b[783] == out[783] is 1.000000 + 2.000000 = 3.000000
a[784] + b[784] == out[784] is 1.000000 + 2.000000 = 3.000000
a[785] + b[785] == out[785] is 1.000000 + 2.000000 = 3.000000
a[786] + b[786] == out[786] is 1.000000 + 2.000000 = 3.000000
a[787] + b[787] == out[787] is 1.000000 + 2.000000 = 3.000000
a[788] + b[788] == out[788] is 1.000000 + 2.000000 = 3.000000
a[789] + b[789] == out[789] is 1.000000 + 2.000000 = 3.000000
a[790] + b[790] == out[790] is 1.000000 + 2.000000 = 3.000000
a[791] + b[791] == out[791] is 1.000000 + 2.000000 = 3.000000
a[792] + b[792] == out[792] is 1.000000 + 2.000000 = 3.000000
a[793] + b[793] == out[793] is 1.000000 + 2.000000 = 3.000000
a[794] + b[794] == out[794] is 1.000000 + 2.000000 = 3.000000
a[795] + b[795] == out[795] is 1.000000 + 2.000000 = 3.000000
a[796] + b[796] == out[796] is 1.000000 + 2.000000 = 3.000000
a[797] + b[797] == out[797] is 1.000000 + 2.000000 = 3.000000
a[798] + b[798] == out[798] is 1.000000 + 2.000000 = 3.000000
a[799] + b[799] == out[799] is 1.000000 + 2.000000 = 3.000000
a[800] + b[800] == out[800] is 1.000000 + 2.000000 = 3.000000
a[801] + b[801] == out[801] is 1.000000 + 2.000000 = 3.000000
a[802] + b[802] == out[802] is 1.000000 + 2.000000 = 3.000000
a[803] + b[803] == out[803] is 1.000000 + 2.000000 = 3.000000
a[804] + b[804] == out[804] is 1.000000 + 2.000000 = 3.000000
a[805] + b[805] == out[805] is 1.000000 + 2.000000 = 3.000000
a[806] + b[806] == out[806] is 1.000000 + 2.000000 = 3.000000
a[807] + b[807] == out[807] is 1.000000 + 2.000000 = 3.000000
a[808] + b[808] == out[808] is 1.000000 + 2.000000 = 3.000000
a[809] + b[809] == out[809] is 1.000000 + 2.000000 = 3.000000
a[810] + b[810] == out[810] is 1.000000 + 2.000000 = 3.000000
a[811] + b[811] == out[811] is 1.000000 + 2.000000 = 3.000000
a[812] + b[812] == out[812] is 1.000000 + 2.000000 = 3.000000
a[813] + b[813] == out[813] is 1.000000 + 2.000000 = 3.000000
a[814] + b[814] == out[814] is 1.000000 + 2.000000 = 3.000000
a[815] + b[815] == out[815] is 1.000000 + 2.000000 = 3.000000
a[816] + b[816] == out[816] is 1.000000 + 2.000000 = 3.000000
a[817] + b[817] == out[817] is 1.000000 + 2.000000 = 3.000000
a[818] + b[818] == out[818] is 1.000000 + 2.000000 = 3.000000
a[819] + b[819] == out[819] is 1.000000 + 2.000000 = 3.000000
a[820] + b[820] == out[820] is 1.000000 + 2.000000 = 3.000000
a[821] + b[821] == out[821] is 1.000000 + 2.000000 = 3.000000
a[822] + b[822] == out[822] is 1.000000 + 2.000000 = 3.000000
a[823] + b[823] == out[823] is 1.000000 + 2.000000 = 3.000000
a[824] + b[824] == out[824] is 1.000000 + 2.000000 = 3.000000
a[825] + b[825] == out[825] is 1.000000 + 2.000000 = 3.000000
a[826] + b[826] == out[826] is 1.000000 + 2.000000 = 3.000000
a[827] + b[827] == out[827] is 1.000000 + 2.000000 = 3.000000
a[828] + b[828] == out[828] is 1.000000 + 2.000000 = 3.000000
a[829] + b[829] == out[829] is 1.000000 + 2.000000 = 3.000000
a[830] + b[830] == out[830] is 1.000000 + 2.000000 = 3.000000
a[831] + b[831] == out[831] is 1.000000 + 2.000000 = 3.000000
a[832] + b[832] == out[832] is 1.000000 + 2.000000 = 3.000000
a[833] + b[833] == out[833] is 1.000000 + 2.000000 = 3.000000
a[834] + b[834] == out[834] is 1.000000 + 2.000000 = 3.000000
a[835] + b[835] == out[835] is 1.000000 + 2.000000 = 3.000000
a[836] + b[836] == out[836] is 1.000000 + 2.000000 = 3.000000
a[837] + b[837] == out[837] is 1.000000 + 2.000000 = 3.000000
a[838] + b[838] == out[838] is 1.000000 + 2.000000 = 3.000000
a[839] + b[839] == out[839] is 1.000000 + 2.000000 = 3.000000
a[840] + b[840] == out[840] is 1.000000 + 2.000000 = 3.000000
a[841] + b[841] == out[841] is 1.000000 + 2.000000 = 3.000000
a[842] + b[842] == out[842] is 1.000000 + 2.000000 = 3.000000
a[843] + b[843] == out[843] is 1.000000 + 2.000000 = 3.000000
a[844] + b[844] == out[844] is 1.000000 + 2.000000 = 3.000000
a[845] + b[845] == out[845] is 1.000000 + 2.000000 = 3.000000
a[846] + b[846] == out[846] is 1.000000 + 2.000000 = 3.000000
a[847] + b[847] == out[847] is 1.000000 + 2.000000 = 3.000000
a[848] + b[848] == out[848] is 1.000000 + 2.000000 = 3.000000
a[849] + b[849] == out[849] is 1.000000 + 2.000000 = 3.000000
a[850] + b[850] == out[850] is 1.000000 + 2.000000 = 3.000000
a[851] + b[851] == out[851] is 1.000000 + 2.000000 = 3.000000
a[852] + b[852] == out[852] is 1.000000 + 2.000000 = 3.000000
a[853] + b[853] == out[853] is 1.000000 + 2.000000 = 3.000000
a[854] + b[854] == out[854] is 1.000000 + 2.000000 = 3.000000
a[855] + b[855] == out[855] is 1.000000 + 2.000000 = 3.000000
a[856] + b[856] == out[856] is 1.000000 + 2.000000 = 3.000000
a[857] + b[857] == out[857] is 1.000000 + 2.000000 = 3.000000
a[858] + b[858] == out[858] is 1.000000 + 2.000000 = 3.000000
a[859] + b[859] == out[859] is 1.000000 + 2.000000 = 3.000000
a[860] + b[860] == out[860] is 1.000000 + 2.000000 = 3.000000
a[861] + b[861] == out[861] is 1.000000 + 2.000000 = 3.000000
a[862] + b[862] == out[862] is 1.000000 + 2.000000 = 3.000000
a[863] + b[863] == out[863] is 1.000000 + 2.000000 = 3.000000
a[864] + b[864] == out[864] is 1.000000 + 2.000000 = 3.000000
a[865] + b[865] == out[865] is 1.000000 + 2.000000 = 3.000000
a[866] + b[866] == out[866] is 1.000000 + 2.000000 = 3.000000
a[867] + b[867] == out[867] is 1.000000 + 2.000000 = 3.000000
a[868] + b[868] == out[868] is 1.000000 + 2.000000 = 3.000000
a[869] + b[869] == out[869] is 1.000000 + 2.000000 = 3.000000
a[870] + b[870] == out[870] is 1.000000 + 2.000000 = 3.000000
a[871] + b[871] == out[871] is 1.000000 + 2.000000 = 3.000000
a[872] + b[872] == out[872] is 1.000000 + 2.000000 = 3.000000
a[873] + b[873] == out[873] is 1.000000 + 2.000000 = 3.000000
a[874] + b[874] == out[874] is 1.000000 + 2.000000 = 3.000000
a[875] + b[875] == out[875] is 1.000000 + 2.000000 = 3.000000
a[876] + b[876] == out[876] is 1.000000 + 2.000000 = 3.000000
a[877] + b[877] == out[877] is 1.000000 + 2.000000 = 3.000000
a[878] + b[878] == out[878] is 1.000000 + 2.000000 = 3.000000
a[879] + b[879] == out[879] is 1.000000 + 2.000000 = 3.000000
a[880] + b[880] == out[880] is 1.000000 + 2.000000 = 3.000000
a[881] + b[881] == out[881] is 1.000000 + 2.000000 = 3.000000
a[882] + b[882] == out[882] is 1.000000 + 2.000000 = 3.000000
a[883] + b[883] == out[883] is 1.000000 + 2.000000 = 3.000000
a[884] + b[884] == out[884] is 1.000000 + 2.000000 = 3.000000
a[885] + b[885] == out[885] is 1.000000 + 2.000000 = 3.000000
a[886] + b[886] == out[886] is 1.000000 + 2.000000 = 3.000000
a[887] + b[887] == out[887] is 1.000000 + 2.000000 = 3.000000
a[888] + b[888] == out[888] is 1.000000 + 2.000000 = 3.000000
a[889] + b[889] == out[889] is 1.000000 + 2.000000 = 3.000000
a[890] + b[890] == out[890] is 1.000000 + 2.000000 = 3.000000
a[891] + b[891] == out[891] is 1.000000 + 2.000000 = 3.000000
a[892] + b[892] == out[892] is 1.000000 + 2.000000 = 3.000000
a[893] + b[893] == out[893] is 1.000000 + 2.000000 = 3.000000
a[894] + b[894] == out[894] is 1.000000 + 2.000000 = 3.000000
a[895] + b[895] == out[895] is 1.000000 + 2.000000 = 3.000000
a[896] + b[896] == out[896] is 1.000000 + 2.000000 = 3.000000
a[897] + b[897] == out[897] is 1.000000 + 2.000000 = 3.000000
a[898] + b[898] == out[898] is 1.000000 + 2.000000 = 3.000000
a[899] + b[899] == out[899] is 1.000000 + 2.000000 = 3.000000
a[900] + b[900] == out[900] is 1.000000 + 2.000000 = 3.000000
a[901] + b[901] == out[901] is 1.000000 + 2.000000 = 3.000000
a[902] + b[902] == out[902] is 1.000000 + 2.000000 = 3.000000
a[903] + b[903] == out[903] is 1.000000 + 2.000000 = 3.000000
a[904] + b[904] == out[904] is 1.000000 + 2.000000 = 3.000000
a[905] + b[905] == out[905] is 1.000000 + 2.000000 = 3.000000
a[906] + b[906] == out[906] is 1.000000 + 2.000000 = 3.000000
a[907] + b[907] == out[907] is 1.000000 + 2.000000 = 3.000000
a[908] + b[908] == out[908] is 1.000000 + 2.000000 = 3.000000
a[909] + b[909] == out[909] is 1.000000 + 2.000000 = 3.000000
a[910] + b[910] == out[910] is 1.000000 + 2.000000 = 3.000000
a[911] + b[911] == out[911] is 1.000000 + 2.000000 = 3.000000
a[912] + b[912] == out[912] is 1.000000 + 2.000000 = 3.000000
a[913] + b[913] == out[913] is 1.000000 + 2.000000 = 3.000000
a[914] + b[914] == out[914] is 1.000000 + 2.000000 = 3.000000
a[915] + b[915] == out[915] is 1.000000 + 2.000000 = 3.000000
a[916] + b[916] == out[916] is 1.000000 + 2.000000 = 3.000000
a[917] + b[917] == out[917] is 1.000000 + 2.000000 = 3.000000
a[918] + b[918] == out[918] is 1.000000 + 2.000000 = 3.000000
a[919] + b[919] == out[919] is 1.000000 + 2.000000 = 3.000000
a[920] + b[920] == out[920] is 1.000000 + 2.000000 = 3.000000
a[921] + b[921] == out[921] is 1.000000 + 2.000000 = 3.000000
a[922] + b[922] == out[922] is 1.000000 + 2.000000 = 3.000000
a[923] + b[923] == out[923] is 1.000000 + 2.000000 = 3.000000
a[924] + b[924] == out[924] is 1.000000 + 2.000000 = 3.000000
a[925] + b[925] == out[925] is 1.000000 + 2.000000 = 3.000000
a[926] + b[926] == out[926] is 1.000000 + 2.000000 = 3.000000
a[927] + b[927] == out[927] is 1.000000 + 2.000000 = 3.000000
a[928] + b[928] == out[928] is 1.000000 + 2.000000 = 3.000000
a[929] + b[929] == out[929] is 1.000000 + 2.000000 = 3.000000
a[930] + b[930] == out[930] is 1.000000 + 2.000000 = 3.000000
a[931] + b[931] == out[931] is 1.000000 + 2.000000 = 3.000000
a[932] + b[932] == out[932] is 1.000000 + 2.000000 = 3.000000
a[933] + b[933] == out[933] is 1.000000 + 2.000000 = 3.000000
a[934] + b[934] == out[934] is 1.000000 + 2.000000 = 3.000000
a[935] + b[935] == out[935] is 1.000000 + 2.000000 = 3.000000
a[936] + b[936] == out[936] is 1.000000 + 2.000000 = 3.000000
a[937] + b[937] == out[937] is 1.000000 + 2.000000 = 3.000000
a[938] + b[938] == out[938] is 1.000000 + 2.000000 = 3.000000
a[939] + b[939] == out[939] is 1.000000 + 2.000000 = 3.000000
a[940] + b[940] == out[940] is 1.000000 + 2.000000 = 3.000000
a[941] + b[941] == out[941] is 1.000000 + 2.000000 = 3.000000
a[942] + b[942] == out[942] is 1.000000 + 2.000000 = 3.000000
a[943] + b[943] == out[943] is 1.000000 + 2.000000 = 3.000000
a[944] + b[944] == out[944] is 1.000000 + 2.000000 = 3.000000
a[945] + b[945] == out[945] is 1.000000 + 2.000000 = 3.000000
a[946] + b[946] == out[946] is 1.000000 + 2.000000 = 3.000000
a[947] + b[947] == out[947] is 1.000000 + 2.000000 = 3.000000
a[948] + b[948] == out[948] is 1.000000 + 2.000000 = 3.000000
a[949] + b[949] == out[949] is 1.000000 + 2.000000 = 3.000000
a[950] + b[950] == out[950] is 1.000000 + 2.000000 = 3.000000
a[951] + b[951] == out[951] is 1.000000 + 2.000000 = 3.000000
a[952] + b[952] == out[952] is 1.000000 + 2.000000 = 3.000000
a[953] + b[953] == out[953] is 1.000000 + 2.000000 = 3.000000
a[954] + b[954] == out[954] is 1.000000 + 2.000000 = 3.000000
a[955] + b[955] == out[955] is 1.000000 + 2.000000 = 3.000000
a[956] + b[956] == out[956] is 1.000000 + 2.000000 = 3.000000
a[957] + b[957] == out[957] is 1.000000 + 2.000000 = 3.000000
a[958] + b[958] == out[958] is 1.000000 + 2.000000 = 3.000000
a[959] + b[959] == out[959] is 1.000000 + 2.000000 = 3.000000
a[960] + b[960] == out[960] is 1.000000 + 2.000000 = 3.000000
a[961] + b[961] == out[961] is 1.000000 + 2.000000 = 3.000000
a[962] + b[962] == out[962] is 1.000000 + 2.000000 = 3.000000
a[963] + b[963] == out[963] is 1.000000 + 2.000000 = 3.000000
a[964] + b[964] == out[964] is 1.000000 + 2.000000 = 3.000000
a[965] + b[965] == out[965] is 1.000000 + 2.000000 = 3.000000
a[966] + b[966] == out[966] is 1.000000 + 2.000000 = 3.000000
a[967] + b[967] == out[967] is 1.000000 + 2.000000 = 3.000000
a[968] + b[968] == out[968] is 1.000000 + 2.000000 = 3.000000
a[969] + b[969] == out[969] is 1.000000 + 2.000000 = 3.000000
a[970] + b[970] == out[970] is 1.000000 + 2.000000 = 3.000000
a[971] + b[971] == out[971] is 1.000000 + 2.000000 = 3.000000
a[972] + b[972] == out[972] is 1.000000 + 2.000000 = 3.000000
a[973] + b[973] == out[973] is 1.000000 + 2.000000 = 3.000000
a[974] + b[974] == out[974] is 1.000000 + 2.000000 = 3.000000
a[975] + b[975] == out[975] is 1.000000 + 2.000000 = 3.000000
a[976] + b[976] == out[976] is 1.000000 + 2.000000 = 3.000000
a[977] + b[977] == out[977] is 1.000000 + 2.000000 = 3.000000
a[978] + b[978] == out[978] is 1.000000 + 2.000000 = 3.000000
a[979] + b[979] == out[979] is 1.000000 + 2.000000 = 3.000000
a[980] + b[980] == out[980] is 1.000000 + 2.000000 = 3.000000
a[981] + b[981] == out[981] is 1.000000 + 2.000000 = 3.000000
a[982] + b[982] == out[982] is 1.000000 + 2.000000 = 3.000000
a[983] + b[983] == out[983] is 1.000000 + 2.000000 = 3.000000
a[984] + b[984] == out[984] is 1.000000 + 2.000000 = 3.000000
a[985] + b[985] == out[985] is 1.000000 + 2.000000 = 3.000000
a[986] + b[986] == out[986] is 1.000000 + 2.000000 = 3.000000
a[987] + b[987] == out[987] is 1.000000 + 2.000000 = 3.000000
a[988] + b[988] == out[988] is 1.000000 + 2.000000 = 3.000000
a[989] + b[989] == out[989] is 1.000000 + 2.000000 = 3.000000
a[990] + b[990] == out[990] is 1.000000 + 2.000000 = 3.000000
a[991] + b[991] == out[991] is 1.000000 + 2.000000 = 3.000000
a[992] + b[992] == out[992] is 1.000000 + 2.000000 = 3.000000
a[993] + b[993] == out[993] is 1.000000 + 2.000000 = 3.000000
a[994] + b[994] == out[994] is 1.000000 + 2.000000 = 3.000000
a[995] + b[995] == out[995] is 1.000000 + 2.000000 = 3.000000
a[996] + b[996] == out[996] is 1.000000 + 2.000000 = 3.000000
a[997] + b[997] == out[997] is 1.000000 + 2.000000 = 3.000000
a[998] + b[998] == out[998] is 1.000000 + 2.000000 = 3.000000
a[999] + b[999] == out[999] is 1.000000 + 2.000000 = 3.000000
a[1000] + b[1000] == out[1000] is 1.000000 + 2.000000 = 3.000000
a[1001] + b[1001] == out[1001] is 1.000000 + 2.000000 = 3.000000
a[1002] + b[1002] == out[1002] is 1.000000 + 2.000000 = 3.000000
a[1003] + b[1003] == out[1003] is 1.000000 + 2.000000 = 3.000000
a[1004] + b[1004] == out[1004] is 1.000000 + 2.000000 = 3.000000
a[1005] + b[1005] == out[1005] is 1.000000 + 2.000000 = 3.000000
a[1006] + b[1006] == out[1006] is 1.000000 + 2.000000 = 3.000000
a[1007] + b[1007] == out[1007] is 1.000000 + 2.000000 = 3.000000
a[1008] + b[1008] == out[1008] is 1.000000 + 2.000000 = 3.000000
a[1009] + b[1009] == out[1009] is 1.000000 + 2.000000 = 3.000000
a[1010] + b[1010] == out[1010] is 1.000000 + 2.000000 = 3.000000
a[1011] + b[1011] == out[1011] is 1.000000 + 2.000000 = 3.000000
a[1012] + b[1012] == out[1012] is 1.000000 + 2.000000 = 3.000000
a[1013] + b[1013] == out[1013] is 1.000000 + 2.000000 = 3.000000
a[1014] + b[1014] == out[1014] is 1.000000 + 2.000000 = 3.000000
a[1015] + b[1015] == out[1015] is 1.000000 + 2.000000 = 3.000000
a[1016] + b[1016] == out[1016] is 1.000000 + 2.000000 = 3.000000
a[1017] + b[1017] == out[1017] is 1.000000 + 2.000000 = 3.000000
a[1018] + b[1018] == out[1018] is 1.000000 + 2.000000 = 3.000000
a[1019] + b[1019] == out[1019] is 1.000000 + 2.000000 = 3.000000
a[1020] + b[1020] == out[1020] is 1.000000 + 2.000000 = 3.000000
a[1021] + b[1021] == out[1021] is 1.000000 + 2.000000 = 3.000000
a[1022] + b[1022] == out[1022] is 1.000000 + 2.000000 = 3.000000
a[1023] + b[1023] == out[1023] is 1.000000 + 2.000000 = 3.000000
Passed
1

对于新到手的项目可以直接放到容器的nginx根目录(快速部署 /usr/share/nginx/html),可以在映射的本机端口进入

2

to my case:

sudo docker run -d -p 80:80 -v /home/sx/Documents/Java/ANANProject/layuimini/:/usr/share/nginx/html/ nginx

title: Cloud Service Computing

#+STARTUP: overview

AWS

Alibaba


title: Blockchain

#+STARTUP: content

BTC: decentralized currency

密码学原理

Crypto-Currency

  1. cryptographic hash function: collision resistance
  2. hidding:
  3. digital commitment : digital equivalent of a sealed envelope
  4. puzzle friendly: nonce : H(block header)<= target for all possible

input

  1. difficult to solve but easy to proof.

SAH256 Secure Hash Algorithm

Count

  1. public key : 加密

  2. private key : 解密 : asymmetric encryption algorithm

Merkel Tree

块内的交易以树的形状存放

节点

重节点

only block header

  1. block header

    version hash of previous block header merkel root hash target nonce

轻节点:Merkel Proof : Merkel Tree

block header block body proof of membership : proof of inclusion

distributed consensus

FLP impossibility result

asynchronous :faulty

CAP theorem

consistency : Avaliability : Partition tolerance

fork

state fork

forking attack : 挖矿时同时挖到两个块 deliberate fork :故意制造的

protocd fork

hard fork : software update : block size limit :

ETH : decentralized contract

memory hard mining puzzle proof of work -> proof of stake SAIC resistance smart contract

Patricia Tree

python

part1

import hashlib
import json

class Block():
    def __init__(self, nonce,tstamp, transcation, prevhash=''):
        self.nonce = nonce
        self.tstamp = tstamp
        self.transcation = transcation
        self.prevhash = prevhash
        self.hash =self.calcHash()
    def __str__(self):
        string = 'nonce:'+str(self.nonce)+'\n'
        string += 'tstamp:'+str(self.tstamp)+'\n'
        string += 'transcation:'+str(self.transcation)+'\n'
        string += 'prevhash:'+str(self.prevhash)+'\n'
        string += 'hash:'+str(self.hash)+'\n'
        return string
    def calcHash(self):
        block_string = json.dumps({'nonce':self.nonce, 'tstamp':self.tstamp, 'transcation':self.transcation, 'prevhash':self.prevhash}, sort_keys=True).encode()
        return hashlib.sha256(block_string).hexdigest()

class Blockchain():
    def __init__(self):
        self.chain=[self.generateGensisBlock(),]
    def generateGensisBlock(self):
        return Block(0,'Fri Oct 26 21:15:12 2018','Gensis Block')
    def getLastBlock(self):
        return self.chain[-1]
    def addBlock(self,newBlock):
        newBlock.prevhash=self.getLastBlock().hash
        newBlock.hash=newBlock.calcHash()
        self.chain.append(newBlock)
    def isChainValid(self):
        for i in range(1,len(self.chain)):
            prevb = self.chain[i-1]
            currb = self.chain[i]
            if(currb.hash != currb.calcHash()):
                print('invalid block')
                return False
            if(currb.prevhash != prevb.hash):
                print('invalid chain')
                return False
        return True


shangCoin = Blockchain()
shangCoin.addBlock(Block(1,'Fri Oct 26 21:22:51 2018',100))
shangCoin.addBlock(Block(2,'Fri Oct 26 21:23:28 2018',200))

shangCoin.chain[1].transcation = 66
print('only change transcation:'+ '\n'+str(shangCoin.chain[1].calcHash()) +'\n'+ str(shangCoin.chain[1].hash))
#如果只是改了一个transaction的值,在执行calcHash之后的结果肯定不等于之前存在hash属性里的结果一致,会报错
shangCoin.chain[1].hash =shangCoin.chain[1].calcHash()
print('after change transcation, and hash all again:'+'\n'+str(shangCoin.chain[2].prevhash)+'\n'+str(shangCoin.chain[1].hash))
#如果在改变transaction后,再hash整个块,则存在下一个块内的prevhash将不会等于这个块内hash变化后的值

for b in shangCoin.chain:
    print(b)
    print(shangCoin.isChainValid())


part2

import hashlib
import json

class Block():
    def __init__(self, nonce,tstamp, transcation, prevhash=''):
        self.nonce = nonce
        self.tstamp = tstamp
        self.transcation = transcation
        self.prevhash = prevhash
        self.hash =self.calcHash()
    def __str__(self):
        string = 'nonce:'+str(self.nonce)+'\n'
        string += 'tstamp:'+str(self.tstamp)+'\n'
        string += 'transcation:'+str(self.transcation)+'\n'
        string += 'prevhash:'+str(self.prevhash)+'\n'
        string += 'hash:'+str(self.hash)+'\n'
        return string
    def calcHash(self):
        block_string = json.dumps({'nonce':self.nonce, 'tstamp':self.tstamp, 'transcation':self.transcation, 'prevhash':self.prevhash}, sort_keys=True).encode()
        return hashlib.sha256(block_string).hexdigest()
    def mineBlock(self,difficult):
        while(self.hash[:difficult] != str('').zfill(difficult)):
            self.nonce += 1
            self.hash = self.calcHash()
            print('the mineBlock is:',self.hash)

class Blockchain():
    def __init__(self):
        self.chain=[self.generateGensisBlock(),]
        self.difficult = 3
    def generateGensisBlock(self):
        return Block(0,'Fri Oct 26 21:15:12 2018','Gensis Block')
    def getLastBlock(self):
        return self.chain[-1]
    def addBlock(self,newBlock):
        newBlock.prevhash=self.getLastBlock().hash
        newBlock.hash=newBlock.calcHash()
        newBlock.mineBlock(self.difficult)
        self.chain.append(newBlock)
    def isChainValid(self):
        for i in range(1,len(self.chain)):
            prevb = self.chain[i-1]
            currb = self.chain[i]
            if(currb.hash != currb.calcHash()):
                print('invalid block')
                return False
            if(currb.prevhash != prevb.hash):
                print('invalid chain')
                return False
        return True


shangCoin = Blockchain()
print('Adding the first block')
shangCoin.addBlock(Block(1,'Fri Oct 26 21:22:51 2018',100))
print('Adding the second block')
shangCoin.addBlock(Block(2,'Fri Oct 26 21:23:28 2018',200))

# shangCoin.chain[1].transcation = 66
# print('only change transcation:'+ '\n'+str(shangCoin.chain[1].calcHash()) +'\n'+ str(shangCoin.chain[1].hash))
# #如果只是改了一个transaction的值,在执行calcHash之后的结果肯定不等于之前存在hash属性里的结果一致,会报错
# shangCoin.chain[1].hash =shangCoin.chain[1].calcHash()
# print('after change transcation, and hash all again:'+'\n'+str(shangCoin.chain[2].prevhash)+'\n'+str(shangCoin.chain[1].hash))
# #如果在改变transaction后,再hash整个块,则存在下一个块内的prevhash将不会等于这个块内hash变化后的值

for b in shangCoin.chain:
    print(b)

if(shangCoin.isChainValid()):

    print('valid blockchain')
else:
    print('hacked blockchain')



part3

import hashlib
import json
from datetime import datetime 
class Transaction():
    def __init__(self, from_address,to_address, amount):
        self.from_address = from_address
        self.to_address = to_address
        self.amount = amount

class Block():
    def __init__(self,tstamp, transcationList, prevhash=''):
        self.nonce = 0
        self.tstamp = tstamp
        self.transcationList = transcationList
        self.prevhash = prevhash
        self.hash =self.calcHash()
    def __str__(self):
        string = 'nonce:'+str(self.nonce)+'\n'
        string += 'tstamp:'+str(self.tstamp)+'\n'
        string += 'transcation:'+str(self.transcation)+'\n'
        string += 'prevhash:'+str(self.prevhash)+'\n'
        string += 'hash:'+str(self.hash)+'\n'
        return string
    def calcHash(self):
        block_string = json.dumps({'nonce':self.nonce, 'tstamp':str(self.tstamp), 'transcation':self.transcationList[0].amount, 'prevhash':self.prevhash}, sort_keys=True).encode()
        return hashlib.sha256(block_string).hexdigest()
    def mineBlock(self,difficult):
        while(self.hash[:difficult] != str('').zfill(difficult)):
            self.nonce += 1
            self.hash = self.calcHash()
            print('the mineBlock is:',self.hash)

class Blockchain():
    def __init__(self):
        self.chain=[self.generateGensisBlock(),]
        self.difficult = 3
        self.pendingTransactions = []
        self.mining_reward = 100

    def generateGensisBlock(self):
        return Block('Fri Oct 26 21:15:12 2018', [Transaction(None,None,0),])

    def getLastBlock(self):
        return self.chain[-1]

    # def addBlock(self,newBlock):
    #     newBlock.prevhash=self.getLastBlock().hash
    #     newBlock.hash=newBlock.calcHash()
    #     newBlock.mineBlock(self.difficult)
    #     self.chain.append(newBlock)
    def minePendingTranaction(self,mining_reward_address):
        block = Block(datetime.now(), self.pendingTransactions)
        block.mineBlock(self.difficult)
        print('Block is mined to get reward:',self.mining_reward)
        self.chain.append(block)
        self.pendingTransactions = [Transaction(None,mining_reward_address, self.mining_reward)]

    def createTransaction(self,T):
        self.pendingTransactions.append(T)

    def getBalence(self,address):
        balance = 0
        for b in self.chain:
            for t in b.transcationList:
                if t.to_address==address:
                    balance += t.amount
                if t.from_address==address:
                    balance -= t.amount
        return balance

    def isChainValid(self):
        for i in range(1,len(self.chain)):
            prevb = self.chain[i-1]
            currb = self.chain[i]
            if(currb.hash != currb.calcHash()):
                print('invalid block')
                return False
            if(currb.prevhash != prevb.hash):
                print('invalid chain')
                return False
        return True


shangCoin = Blockchain()
shangCoin.createTransaction(Transaction('address1', 'address2',100))
shangCoin.createTransaction(Transaction('address2', 'address1',50))
print('starting mining:')
shangCoin.minePendingTranaction('shangaddress')
print('shangCoin miner balance is:', shangCoin.getBalence('shangaddress'))

shangCoin.createTransaction(Transaction('address1', 'address2',200))
shangCoin.createTransaction(Transaction('address2', 'address1',150))
print('starting mining again:')
shangCoin.minePendingTranaction('shangaddress')
print('shangCoin miner balance is:', shangCoin.getBalence('shangaddress'))


part4 (has error)

import hashlib
import json
from datetime import datetime 
from flask import Flask
from flask import jsonify
from time import time

class Block():
    def __init__(self, nonce, tstamp, transationList, prevhash='', hash =''):
        self.nonce = nonce
        self.tstamp = tstamp
        self.transationList = transationList
        self.prevhash = prevhash
        if hash == '':
            self.hash = self.calcHash
        else:
            self.hash =hash

    def toDict(self):
        return {'nonce':self.nonce, 'tstamp':str(self.tstamp), 'transation':self.transationList, 'prevhash':self.prevhash, 'hash':self.hash}

    def calcHash(self):
        block_string = json.dumps({'nonce':self.nonce, 'tstamp':str(self.tstamp), 'transation':self.transationList, 'prevhash':self.prevhash}, sort_keys=True).encode()
        return hashlib.sha256(block_string).hexdigest()
    def mineBlock(self, difficult):
        while(self.hash[:difficult] != str('').zfill(difficult)):
            self.nonce += 1
            self.hash = self.calcHash()
            print('the mineBlock is:',self.hash)

class Blockchain():
    def __init__(self):
        self.chain=[]
        self.difficult=3
        self.pendingTransations = []
        self.mining_reward = 100
        self.generateGensisBlock()
    def generateGensisBlock(self):
        dect = {'nonce':0, 'tstamp':'Sun Oct 28 12:54:03 2018', 'transationList':[{'from_address':None, 'to_address':None, 'amount':0},],'hash':''}
        b = Block(**dect)
        self.chain.append(b.toDict())

    def getLastBlock(self):
        return Block(**self.chain[-1])

    def minePendingTransation(self, mining_reward_address):
        self.pendingTransations = [{'from_address':None,'to_address':mining_reward_address,'amount':self.mining_reward},]
        block = Block(0, str(datetime.now()),self.pendingTransations)
        block.prevhash = self.getLastBlock().hash
        block.mineBlock(self.difficult)
        print('Block is mined to get reward:',self.mining_reward)
        self.chain.append(block.toDict())

    def createTransation(self, from_address, to_address,amount):
        self.pendingTransations.append({'from_adress':from_address,'to_address':to_address, 'amount':amount})

    def getBalence(self,address):
        balance = 0
        for index in range(len(self.chain)):
            dictList=self.chain[index]['transationList']
            for dic in dictList:
                if dic['to_address']==address:
                    balance += dic['amount']
                if dic['from_address']==address:
                    balance -= dic['amount']
        return balance

    def isChainValid(self):
        for i in range(1,len(self.chain)):
            prevb =Block(**self.chain[i-1])
            currb =Block(**self.chain[i])
            if(currb.hash != currb.calcHash()):
                print('invalid block')
                return False
            if(currb.prevhash != prevb.hash):
                print('invalid chain')
                return False
        return True


shangCoin = Blockchain()
shangCoin.createTransation('address1', 'address2',100)
shangCoin.createTransation('address2', 'address1',50)
print('starting mining:')
shangCoin.minePendingTransation("shangaddress")
print('shangCoin miner balance is:', shangCoin.getBalence("shangaddress"))
print(shangCoin.isChainValid())


title: Data Science and Cloud Service Computing

#+STARTUP: overview

Hadoop

one node installation

.bashrc

export HADOOP_HOME=/home/cloud/hadoop-3.3.1
export HADOOP_INSTALL=<span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8778em;vertical-align:-0.1944em;"></span><span class="mord mathnormal" style="margin-right:0.08125em;">H</span><span class="mord mathnormal">A</span><span class="mord mathnormal" style="margin-right:0.02778em;">D</span><span class="mord mathnormal" style="margin-right:0.02778em;">OO</span><span class="mord"><span class="mord mathnormal" style="margin-right:0.13889em;">P</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3283em;"><span style="top:-2.55em;margin-left:-0.1389em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight" style="margin-right:0.08125em;">H</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mord mathnormal" style="margin-right:0.05764em;">OME</span><span class="mord mathnormal">e</span><span class="mord mathnormal">x</span><span class="mord mathnormal">p</span><span class="mord mathnormal" style="margin-right:0.02778em;">or</span><span class="mord mathnormal">t</span><span class="mord mathnormal" style="margin-right:0.08125em;">H</span><span class="mord mathnormal">A</span><span class="mord mathnormal" style="margin-right:0.02778em;">D</span><span class="mord mathnormal" style="margin-right:0.02778em;">OO</span><span class="mord"><span class="mord mathnormal" style="margin-right:0.13889em;">P</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3283em;"><span style="top:-2.55em;margin-left:-0.1389em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight" style="margin-right:0.10903em;">M</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mord mathnormal">A</span><span class="mord mathnormal" style="margin-right:0.05764em;">PRE</span><span class="mord"><span class="mord mathnormal" style="margin-right:0.02778em;">D</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3283em;"><span style="top:-2.55em;margin-left:-0.0278em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight" style="margin-right:0.08125em;">H</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mord mathnormal" style="margin-right:0.05764em;">OME</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">=</span></span></span></span>HADOOP_HOME
export HADOOP_COMMON_HOME=<span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8778em;vertical-align:-0.1944em;"></span><span class="mord mathnormal" style="margin-right:0.08125em;">H</span><span class="mord mathnormal">A</span><span class="mord mathnormal" style="margin-right:0.02778em;">D</span><span class="mord mathnormal" style="margin-right:0.02778em;">OO</span><span class="mord"><span class="mord mathnormal" style="margin-right:0.13889em;">P</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3283em;"><span style="top:-2.55em;margin-left:-0.1389em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight" style="margin-right:0.08125em;">H</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mord mathnormal" style="margin-right:0.05764em;">OME</span><span class="mord mathnormal">e</span><span class="mord mathnormal">x</span><span class="mord mathnormal">p</span><span class="mord mathnormal" style="margin-right:0.02778em;">or</span><span class="mord mathnormal">t</span><span class="mord mathnormal" style="margin-right:0.08125em;">H</span><span class="mord mathnormal">A</span><span class="mord mathnormal" style="margin-right:0.02778em;">D</span><span class="mord mathnormal" style="margin-right:0.02778em;">OO</span><span class="mord"><span class="mord mathnormal" style="margin-right:0.13889em;">P</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3283em;"><span style="top:-2.55em;margin-left:-0.1389em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight" style="margin-right:0.08125em;">H</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mord mathnormal" style="margin-right:0.02778em;">D</span><span class="mord mathnormal" style="margin-right:0.13889em;">F</span><span class="mord"><span class="mord mathnormal" style="margin-right:0.05764em;">S</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3283em;"><span style="top:-2.55em;margin-left:-0.0576em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight" style="margin-right:0.08125em;">H</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mord mathnormal" style="margin-right:0.05764em;">OME</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">=</span></span></span></span>HADOOP_HOME
export YARN_HOME=<span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8778em;vertical-align:-0.1944em;"></span><span class="mord mathnormal" style="margin-right:0.08125em;">H</span><span class="mord mathnormal">A</span><span class="mord mathnormal" style="margin-right:0.02778em;">D</span><span class="mord mathnormal" style="margin-right:0.02778em;">OO</span><span class="mord"><span class="mord mathnormal" style="margin-right:0.13889em;">P</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3283em;"><span style="top:-2.55em;margin-left:-0.1389em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight" style="margin-right:0.08125em;">H</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mord mathnormal" style="margin-right:0.05764em;">OME</span><span class="mord mathnormal">e</span><span class="mord mathnormal">x</span><span class="mord mathnormal">p</span><span class="mord mathnormal" style="margin-right:0.02778em;">or</span><span class="mord mathnormal">t</span><span class="mord mathnormal" style="margin-right:0.08125em;">H</span><span class="mord mathnormal">A</span><span class="mord mathnormal" style="margin-right:0.02778em;">D</span><span class="mord mathnormal" style="margin-right:0.02778em;">OO</span><span class="mord"><span class="mord mathnormal" style="margin-right:0.13889em;">P</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3283em;"><span style="top:-2.55em;margin-left:-0.1389em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight" style="margin-right:0.07153em;">C</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mord mathnormal" style="margin-right:0.02778em;">OMMO</span><span class="mord"><span class="mord mathnormal" style="margin-right:0.10903em;">N</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3283em;"><span style="top:-2.55em;margin-left:-0.109em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight">L</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mord mathnormal" style="margin-right:0.07847em;">I</span><span class="mord"><span class="mord mathnormal" style="margin-right:0.05017em;">B</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3283em;"><span style="top:-2.55em;margin-left:-0.0502em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight" style="margin-right:0.10903em;">N</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mord mathnormal">A</span><span class="mord mathnormal" style="margin-right:0.13889em;">T</span><span class="mord mathnormal" style="margin-right:0.07847em;">I</span><span class="mord mathnormal" style="margin-right:0.22222em;">V</span><span class="mord"><span class="mord mathnormal" style="margin-right:0.05764em;">E</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3283em;"><span style="top:-2.55em;margin-left:-0.0576em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight" style="margin-right:0.02778em;">D</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mord mathnormal" style="margin-right:0.07847em;">I</span><span class="mord mathnormal" style="margin-right:0.00773em;">R</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">=</span></span></span></span>HADOOP_HOME/lib/native
export PATH=<span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6833em;"></span><span class="mord mathnormal" style="margin-right:0.13889em;">P</span><span class="mord mathnormal">A</span><span class="mord mathnormal" style="margin-right:0.13889em;">T</span><span class="mord mathnormal" style="margin-right:0.08125em;">H</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">:</span></span></span></span>HADOOP_HOME/sbin:<span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord mathnormal" style="margin-right:0.08125em;">H</span><span class="mord mathnormal">A</span><span class="mord mathnormal" style="margin-right:0.02778em;">D</span><span class="mord mathnormal" style="margin-right:0.02778em;">OO</span><span class="mord"><span class="mord mathnormal" style="margin-right:0.13889em;">P</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3283em;"><span style="top:-2.55em;margin-left:-0.1389em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight" style="margin-right:0.08125em;">H</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mord mathnormal" style="margin-right:0.05764em;">OME</span><span class="mord">/</span><span class="mord mathnormal">bin</span><span class="mord mathnormal">e</span><span class="mord mathnormal">x</span><span class="mord mathnormal">p</span><span class="mord mathnormal" style="margin-right:0.02778em;">or</span><span class="mord mathnormal">t</span><span class="mord mathnormal" style="margin-right:0.08125em;">H</span><span class="mord mathnormal">A</span><span class="mord mathnormal" style="margin-right:0.02778em;">D</span><span class="mord mathnormal" style="margin-right:0.02778em;">OO</span><span class="mord"><span class="mord mathnormal" style="margin-right:0.13889em;">P</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3283em;"><span style="top:-2.55em;margin-left:-0.1389em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight" style="margin-right:0.02778em;">O</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mord mathnormal" style="margin-right:0.05764em;">PTS</span><span class="mord">&quot;</span><span class="mspace" style="margin-right:0.2222em;"></span><span class="mbin">−</span><span class="mspace" style="margin-right:0.2222em;"></span></span><span class="base"><span class="strut" style="height:0.8889em;vertical-align:-0.1944em;"></span><span class="mord mathnormal" style="margin-right:0.02778em;">D</span><span class="mord mathnormal">ja</span><span class="mord mathnormal" style="margin-right:0.03588em;">v</span><span class="mord mathnormal">a</span><span class="mord">.</span><span class="mord mathnormal" style="margin-right:0.01968em;">l</span><span class="mord mathnormal">ib</span><span class="mord mathnormal" style="margin-right:0.02778em;">r</span><span class="mord mathnormal">a</span><span class="mord mathnormal" style="margin-right:0.03588em;">ry</span><span class="mord">.</span><span class="mord mathnormal">p</span><span class="mord mathnormal">a</span><span class="mord mathnormal">t</span><span class="mord mathnormal">h</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">=</span></span></span></span>HADOOP_HOME/lib/nativ"

$HADOOP~HOME~/etc/hadoop/hadoop-env.sh

append to end

export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64

$HADOOP~HOME~/etc/hadoop/core-site.xml

in configuration

<property>
     <name>hadoop.tmp.dir</name>
     <value>/home/cloud/tmpdata</value>
     <description>A base for other temporary directories.</description>
 </property>
 <property>
     <name>fs.default.name</name>
     <value>hdfs://localhost:9000</value>
     <description>The name of the default file system></description>
 </property>

$HADOOP~HOME~/etc/hadoop/hdfs-site.xml

in configuration

<property>
  <name>dfs.data.dir</name>
  <value>/home/cloud/dfsdata/namenode</value>
</property>
<property>
  <name>dfs.data.dir</name>
  <value>/home/cloud/dfsdata/datanode</value>
</property>
<property>
  <name>dfs.replication</name>
  <value>1</value>
</property>

$HADOOP~HOME~/etc/hadoop/mapred-site.xml

in configuration

<property>
  <name>mapreduce.framework.name</name>
  <value>yarn</value>
</property>

$HADOOP~HOME~/etc/hadoop/yarn-site.xml

<property>
  <name>yarn.nodemanager.aux-services</name>
  <value>mapreduce_shuffle</value>
</property>
<property>
  <name>yarn.nodemanager.aux-services.mapreduce.shuffle.class</name>
  <value>org.apache.hadoop.mapred.ShuffleHandler</value>
</property>
<property>
  <name>yarn.resourcemanager.hostname</name>
  <value>127.0.0.1</value>
</property>
<property>
  <name>yarn.acl.enable</name>
  <value>0</value>
</property>
<property>
  <name>yarn.nodemanager.env-whitelist</name>
  <value>JAVA_HOME,HADOOP_COMMON_HOME,HADOOP_HDFS_HOME,HADOOP_CONF_DIR,CLASSPATH_PERPEND_DISTCACHE,HADOOP_YARN_HOME,HADOOP_MAPRED_HOME</value>
</property>

init nodename

cd hadoop-3---
hdfs namenode -format
cd sbin
./start-dfs.sh
./start-yarn.sh
jps

3 node installation

GWDG deployment

software .1 .10 .19


hadoop hadoop1 hadoop2 hadoop3 hostname project q3lb q3l HDFS Namenode NameNode SecondaryNameNode HDFS DataNode DataNode DataNode DataNode YARN ResourceM ResourceManager
YARN NodeM NodeManager NodeManager NodeManager

.bashrc

export HADOOP_HOME=/home/cloud/hadoop-3.3.1
export HADOOP_INSTALL=<span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8778em;vertical-align:-0.1944em;"></span><span class="mord mathnormal" style="margin-right:0.08125em;">H</span><span class="mord mathnormal">A</span><span class="mord mathnormal" style="margin-right:0.02778em;">D</span><span class="mord mathnormal" style="margin-right:0.02778em;">OO</span><span class="mord"><span class="mord mathnormal" style="margin-right:0.13889em;">P</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3283em;"><span style="top:-2.55em;margin-left:-0.1389em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight" style="margin-right:0.08125em;">H</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mord mathnormal" style="margin-right:0.05764em;">OME</span><span class="mord mathnormal">e</span><span class="mord mathnormal">x</span><span class="mord mathnormal">p</span><span class="mord mathnormal" style="margin-right:0.02778em;">or</span><span class="mord mathnormal">t</span><span class="mord mathnormal" style="margin-right:0.08125em;">H</span><span class="mord mathnormal">A</span><span class="mord mathnormal" style="margin-right:0.02778em;">D</span><span class="mord mathnormal" style="margin-right:0.02778em;">OO</span><span class="mord"><span class="mord mathnormal" style="margin-right:0.13889em;">P</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3283em;"><span style="top:-2.55em;margin-left:-0.1389em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight" style="margin-right:0.10903em;">M</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mord mathnormal">A</span><span class="mord mathnormal" style="margin-right:0.05764em;">PRE</span><span class="mord"><span class="mord mathnormal" style="margin-right:0.02778em;">D</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3283em;"><span style="top:-2.55em;margin-left:-0.0278em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight" style="margin-right:0.08125em;">H</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mord mathnormal" style="margin-right:0.05764em;">OME</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">=</span></span></span></span>HADOOP_HOME
export HADOOP_COMMON_HOME=<span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8778em;vertical-align:-0.1944em;"></span><span class="mord mathnormal" style="margin-right:0.08125em;">H</span><span class="mord mathnormal">A</span><span class="mord mathnormal" style="margin-right:0.02778em;">D</span><span class="mord mathnormal" style="margin-right:0.02778em;">OO</span><span class="mord"><span class="mord mathnormal" style="margin-right:0.13889em;">P</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3283em;"><span style="top:-2.55em;margin-left:-0.1389em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight" style="margin-right:0.08125em;">H</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mord mathnormal" style="margin-right:0.05764em;">OME</span><span class="mord mathnormal">e</span><span class="mord mathnormal">x</span><span class="mord mathnormal">p</span><span class="mord mathnormal" style="margin-right:0.02778em;">or</span><span class="mord mathnormal">t</span><span class="mord mathnormal" style="margin-right:0.08125em;">H</span><span class="mord mathnormal">A</span><span class="mord mathnormal" style="margin-right:0.02778em;">D</span><span class="mord mathnormal" style="margin-right:0.02778em;">OO</span><span class="mord"><span class="mord mathnormal" style="margin-right:0.13889em;">P</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3283em;"><span style="top:-2.55em;margin-left:-0.1389em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight" style="margin-right:0.08125em;">H</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mord mathnormal" style="margin-right:0.02778em;">D</span><span class="mord mathnormal" style="margin-right:0.13889em;">F</span><span class="mord"><span class="mord mathnormal" style="margin-right:0.05764em;">S</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3283em;"><span style="top:-2.55em;margin-left:-0.0576em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight" style="margin-right:0.08125em;">H</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mord mathnormal" style="margin-right:0.05764em;">OME</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">=</span></span></span></span>HADOOP_HOME
export YARN_HOME=<span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8778em;vertical-align:-0.1944em;"></span><span class="mord mathnormal" style="margin-right:0.08125em;">H</span><span class="mord mathnormal">A</span><span class="mord mathnormal" style="margin-right:0.02778em;">D</span><span class="mord mathnormal" style="margin-right:0.02778em;">OO</span><span class="mord"><span class="mord mathnormal" style="margin-right:0.13889em;">P</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3283em;"><span style="top:-2.55em;margin-left:-0.1389em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight" style="margin-right:0.08125em;">H</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mord mathnormal" style="margin-right:0.05764em;">OME</span><span class="mord mathnormal">e</span><span class="mord mathnormal">x</span><span class="mord mathnormal">p</span><span class="mord mathnormal" style="margin-right:0.02778em;">or</span><span class="mord mathnormal">t</span><span class="mord mathnormal" style="margin-right:0.08125em;">H</span><span class="mord mathnormal">A</span><span class="mord mathnormal" style="margin-right:0.02778em;">D</span><span class="mord mathnormal" style="margin-right:0.02778em;">OO</span><span class="mord"><span class="mord mathnormal" style="margin-right:0.13889em;">P</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3283em;"><span style="top:-2.55em;margin-left:-0.1389em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight" style="margin-right:0.07153em;">C</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mord mathnormal" style="margin-right:0.02778em;">OMMO</span><span class="mord"><span class="mord mathnormal" style="margin-right:0.10903em;">N</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3283em;"><span style="top:-2.55em;margin-left:-0.109em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight">L</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mord mathnormal" style="margin-right:0.07847em;">I</span><span class="mord"><span class="mord mathnormal" style="margin-right:0.05017em;">B</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3283em;"><span style="top:-2.55em;margin-left:-0.0502em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight" style="margin-right:0.10903em;">N</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mord mathnormal">A</span><span class="mord mathnormal" style="margin-right:0.13889em;">T</span><span class="mord mathnormal" style="margin-right:0.07847em;">I</span><span class="mord mathnormal" style="margin-right:0.22222em;">V</span><span class="mord"><span class="mord mathnormal" style="margin-right:0.05764em;">E</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3283em;"><span style="top:-2.55em;margin-left:-0.0576em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight" style="margin-right:0.02778em;">D</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mord mathnormal" style="margin-right:0.07847em;">I</span><span class="mord mathnormal" style="margin-right:0.00773em;">R</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">=</span></span></span></span>HADOOP_HOME/lib/native
export PATH=<span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6833em;"></span><span class="mord mathnormal" style="margin-right:0.13889em;">P</span><span class="mord mathnormal">A</span><span class="mord mathnormal" style="margin-right:0.13889em;">T</span><span class="mord mathnormal" style="margin-right:0.08125em;">H</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">:</span></span></span></span>HADOOP_HOME/sbin:<span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord mathnormal" style="margin-right:0.08125em;">H</span><span class="mord mathnormal">A</span><span class="mord mathnormal" style="margin-right:0.02778em;">D</span><span class="mord mathnormal" style="margin-right:0.02778em;">OO</span><span class="mord"><span class="mord mathnormal" style="margin-right:0.13889em;">P</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3283em;"><span style="top:-2.55em;margin-left:-0.1389em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight" style="margin-right:0.08125em;">H</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mord mathnormal" style="margin-right:0.05764em;">OME</span><span class="mord">/</span><span class="mord mathnormal">bin</span><span class="mord mathnormal">e</span><span class="mord mathnormal">x</span><span class="mord mathnormal">p</span><span class="mord mathnormal" style="margin-right:0.02778em;">or</span><span class="mord mathnormal">t</span><span class="mord mathnormal" style="margin-right:0.08125em;">H</span><span class="mord mathnormal">A</span><span class="mord mathnormal" style="margin-right:0.02778em;">D</span><span class="mord mathnormal" style="margin-right:0.02778em;">OO</span><span class="mord"><span class="mord mathnormal" style="margin-right:0.13889em;">P</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3283em;"><span style="top:-2.55em;margin-left:-0.1389em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight" style="margin-right:0.02778em;">O</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mord mathnormal" style="margin-right:0.05764em;">PTS</span><span class="mord">&quot;</span><span class="mspace" style="margin-right:0.2222em;"></span><span class="mbin">−</span><span class="mspace" style="margin-right:0.2222em;"></span></span><span class="base"><span class="strut" style="height:0.8889em;vertical-align:-0.1944em;"></span><span class="mord mathnormal" style="margin-right:0.02778em;">D</span><span class="mord mathnormal">ja</span><span class="mord mathnormal" style="margin-right:0.03588em;">v</span><span class="mord mathnormal">a</span><span class="mord">.</span><span class="mord mathnormal" style="margin-right:0.01968em;">l</span><span class="mord mathnormal">ib</span><span class="mord mathnormal" style="margin-right:0.02778em;">r</span><span class="mord mathnormal">a</span><span class="mord mathnormal" style="margin-right:0.03588em;">ry</span><span class="mord">.</span><span class="mord mathnormal">p</span><span class="mord mathnormal">a</span><span class="mord mathnormal">t</span><span class="mord mathnormal">h</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">=</span></span></span></span>HADOOP_HOME/lib/nativ"

$HADOOP~HOME~/etc/hadoop/hadoop-env.sh

append to end

export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64

$HADOOP~HOME~/etc/hadoop/core-site.xml

in configuration

<property>
     <name>hadoop.tmp.dir</name>
     <value>/home/cloud/hadoop-3.3.1/data</value>
     <description>A base for other temporary directories.</description>
 </property>
 <property>
     <name>fs.default.name</name>
     <value>hdfs://hostname:9000</value> watch out for inter floatip for localhost 
     <description>The name of the default file system></description>
 </property>

$HADOOP~HOME~/etc/hadoop/hdfs-site.xml

in configuration

<property>
  <name>dfs.data.dir</name>
  <value>/home/cloud/hahoop-3.3.1/dfsdata/namenode</value>
</property>
<property>
  <name>dfs.data.dir</name>
  <value>/home/cloud/hahoop-3.3.1/dfsdata/datanode</value>
</property>
<property>
  <name>dfs.replication</name>
  <value>3</value>
</property>
<property>
  <name>dfs.namenode.http-address</name>
  <value>*inter floatip:9870*</value>
</property>
<property>
  <name>dfs.namenode.secondary.http-address</name>
  <value>inter floatip:9868</value>
</property>

$HADOOP~HOME~/etc/hadoop/yarn-site.xml

<property>
  <name>yarn.nodemanager.aux-services</name>
  <value>mapreduce_shuffle</value>
</property>
<property>
  <name>yarn.nodemanager.aux-services.mapreduce.shuffle.class</name>
  <value>org.apache.hadoop.mapred.ShuffleHandler</value>
</property>
<property>
  <name>yarn.resourcemanager.hostname</name>
  <value>*inter floatip*</value>
</property>
<property>
  <name>yarn.acl.enable</name>
  <value>0</value>
</property>
<property>
  <name>yarn.nodemanager.env-whitelist</name>
  <value>JAVA_HOME,HADOOP_COMMON_HOME,HADOOP_HDFS_HOME,HADOOP_CONF_DIR,CLASSPATH_PERPEND_DISTCACHE,HADOOP_YARN_HOME,HADOOP_MAPRED_HOME</value>
</property>

$HADOOP~HOME~/etc/hadoop/mapred-site.xml

in configuration

<property>
  <name>mapreduce.framework.name</name>
  <value>yarn</value>
</property>

$HADOOP~HOME~/etc/hadoop/wores

gwdg01 gwdg10 gwdg19

init nodename

cd hadoop-3---
xsycn etc/hadoop
hdfs namenode -format
cd sbin
./start-dfs.sh
./start-yarn.sh
jps

command

general comands

hdfs dfs -ls /
hdfs dfs -chmod 777 /testFolder
hdfs dfs -cat /tesFolder/text.txt
hdfs dfs -get hdfspath localpath
hdfs dfs -put localpath hdfspath
hdfs dfsadmin -report
hdfs fsck /

word example

hadoop jar share/hadoop/mapreduce/hadoop-mapreduce-examples-3.3.1.jar wordcount /input /output/
hadoop fs -cat /output/part-r-00000
cd output
hadoop fs -getmerge /hpda04-2.3-output/ out
cat out

map()

map(fun <key1, val1>) -> list(<key2, val2>) to a list of key-value pairs all elemenet in list must have the same type

Schuffle

schuffle(list(<key2, val2>)) -> list(<key2, list(val2)>)

reduce

reduce (fun, list(<key2, list(val2)>)) -> list(val3)

Limitation

1, multiple map() and reduce() must be manually specified 2, intermediary results has to be written to the HDFS, not on memory iterative algorithms are not very efficient with Hadoop.

HDFS

descripation

Hadoop distributed file system
Namenode vs Datanodes

1, high throughout with low latency
2, support large file
3, locally computation in Node, less transfer zwischen Nodes
4, resilient design for hardware failurs

install

tut link https://drive.google.com/drive/folders/1XdPbyAc9iWml0fPPNX91Yq3BRwkZAG2M

java
ssh localhost(ssh-keygen -t rsa)
edit 6 file
./hdfs  namenode -format

YARN

Yet Another Resource Negotiator Resource Manager vs NodeManager Resource Manager avoid overutilization and underutilization The NodeManager execute tasks on the local resources 1, Client send a requirement to Resource Manager 2, Resource manager allocate container in Node Manager 3, Container in Node Manager start the application Master 4, Application Master require Resource from Resoure Manager 5, as the required Resoure is allocated, application master start the Application

Spark

3 node installation

GWDG deployment

floatip .1 .10 .19


hostname gwdg01 gwdg10 gwdg19 ip .8 .5 .10 HDFS Namenode NameNode SecondaryNameNode HDFS DataNode DataNode DataNode DataNode YARN ResourceM ResourceManager
YARN NodeM NodeManager NodeManager NodeManager

descripation

results do not need to save in HDFS, it support in memory executation. Resilient Distributed Datasets RDDS DataFrame from SparkSQL

scala

can from binary file can from source file can from IDEA blugin can from spark installation

install

from source

this is a full eco system, can build a cluster by my own, with embended scala

from pip

my Prof can also build a eco system in pip download file, with config in master: spark-submit --deploy-mode --master yarn test.py But I can't, I can even not find conf file in pip file for pyspark, if you still want to consturcte a cluster, use spark installation from source file, like following

single master node configuration with

cat ~/Documents/spark/myown/test.py

print("hello world")

cd .../spark
./sbin/start-all
curl localhost:8080(spark-url for master)
./bin/spark-submit --master spark-url ./myown/test.py

test.py will be executed

./bin/pyspark --master spark-url 

will open a terminal with master configuration

pyspark

cd spark
bin/spark-submit examples/src/main/python/wordcount.py testtext.txt &> output.txt

Big data lecture

Association Rule Minning

  • Transaction: T, one behavior, which accomplished a lot of things(items) -transaction instances t,
  • Item : I, which stands for the smallest unit, that can be done.
  • Our task is to find out, the relationship between items

Support the probabilty of a itemset occurs All IS bigger than a setted value is called frequent itemset, but how to set the value is self-define

Confidence

the Probabilities  If a is done, b will also be done.

Support

a and b be done together from all Transaction, identify the special Transaction case

practicability (Lift)

The impact of a on b to be done

Aprioir algorithm

1.(with support level(S) )

  • find the frequently itemset(L)
  • the subsets of frequently itemset is also frequently itemset
  • collect the total Transaction set(T), and set the the support level
  • find all , which satisfied S,
  • find all , which come from all 2-items combinations, which satisfied S
  • .....to only one left, .

2.(with Confidence (C) )find all subsets of , which satisfied C.

Note all the operations in this 2 step is done in the whole Transaction sets

Data Exploration

Singal feather: histogram density, rug, Box-Whisker Box-Whisker: low quartile to high quartile is interquartile range (IQR)

low boundary: low quartile - IQR high boundary: high quartile + IQR

pair-wise scatterplot

hexbin plot

correlation heatmap

Time Series Analysis

Descripation

Discrete values {,....,$x~T~$} = A core assumpation is the time difference between and is equal for . can be decomposed into 3 components:


1. trend component T change over all time 2. seasonality S the results of seasons effect 3. autocorrelation R how the values depends on prior values


so

Box-Jenkins for stationary

  1. stationary

    Time series is stationary Mean and Variance of the trend and seasonality are constant and can be removed so the autocorrelation is stochastic process,

  2. Trend and Series Effects

    1. model the trend on the time series
    2. detrended time series
    3. model the seasonality on the time series
    4. get the seasonality adjusted time series
  3. Regession and Seasonal Means

    In this context we can only use linear regession to fit the all time series, get .

    and then substract the seasonal Means: is special for mod(t, s), in the recursive seasonal effect, only the same time slot element will be calculated, this happens if the last season is not complete.

    Cons only works for linear trends and with seasonal effects that have no trend.

Differencing for not stationary

for for two points(, ) and (), the first-order difference to detrended time series: . or if you want, you can get the second-order-difference

using difference to adjust the seasonal effect: using the difference between two consecutive points in time during the season.

pro it can deal with both changes in the mean, as well as changes in the movement of the mean

Correlation

Autocorrelation is the direct relationship of the values of the time series at different points in time, for two adjacent points

Partial autocorrelation is the autocorrelation without the carryover, i.e., only the direct correlation, not for two adjacent points

for Authentication and Partial authentication we can see the residual seasonal effect for regession and seasonal means

ARIMA

three ways to model correlation

  1. AR: atuoregressive

    model the direct influence of the past p points on time series c :constant over all time : white noise, mean of 0, normal distribution

  2. MA: Moving average

    model the random effect on time series the difference is the random influence of the past noise to next value

  3. ARMA: autoregressive and Moving average

  4. select p and q

    partial authentication estimate the p for AR, but if p can cover all the season, but if p is too big, it can lead to overfitting.

    autocorrelation can estimate the q for MA, using q as the steps for autocorrelation to be 0, so we look at when the autocorrelation goes towards zero and use this for q. at the same time the effect of AR should also be counted for determinate q.

Text minning

Preprocessing

  1. Creation of a Corpus

    contains all text to analysis

  2. remove the irrelevant content,

    links, timestamps

  3. Punctuation and Cases

    remove all Punctuation, and all use small cases a problem is about acronyms

  4. Stop words

    commons words should be removed, auch as I, to ,a

  5. Stemming and Lemmatization

    first Lemmatization, and then Stemming

Visualiztation

  1. bag-of-words with wordclouds

  2. Term frequency(TF)

    is the count of a words within document

  3. Inverse Document Frequency(IDF)

    is to weight words by their uniqueness within the corpus t: word(term) N: the number of document in corpus : the number of document in corpus, which contains word t

  4. TFIDF

  5. beyond the bag-of-words

    ignore the structure of document ignore simiarity of words

challages

  1. dimensionality

  2. Ambiguities

Sensor Fusion lecture

Sensor Dataverarbeitung

Tensor Fehler, Präzision: stochastisch Richtigkeit: systematisch

concepts


competitive many sensor for the same place für higher accuracy complementary many sensor for many places für higher completeness dead reckoning errors accumulation over previous knowlegde



measurement equation projects the state onto the measurement space y measurement x state H measurement matrix e measurement error


Jacobian Matrix one order

Hessian Matrix two order

Partial Matrix

data analysis code demo

statistical mothode

from scipy import stats
from scipy.stats import norm
import numpy as np
import scipy as sp
print(sp.stats.t.ppf(0.95,6))
print(norm.cdf([-1,0,1]))
print(norm.cdf(np.array([-1,0,1])))
print(norm.mean(), norm.std(), norm.var() )
print(norm.pdf(0))
print(norm.cdf(1.96))
print(norm.ppf(0.975))
print(norm.cdf(1))
print(norm.ppf(0.841344746090))
print(norm.sf(1-norm.cdf(1)))
print(norm.ppf(0.9))
print(stats.t.ppf(0.975,3))
print(stats.t.ppf(0.975,3))

confidence level interval determinate

import numpy as np
import scipy as sp
import scipy.stats

b = [8*x**0 for x in range(200)] + np.random.normal(0, 0.05, (200))


def t_stastik(data, confidence):
    m, se = np.mean(data), sp.stats.sem(data)
    h = se*sp.stats.t.isf((1-confidence)/2. , df = (len(data)-1) )
    return m, m-h, m+h
print(" For given data sete we have their mean  with 95% confidence level of region :",t_stastik(b,0.95))

def mean_confidence_interval(data, confidence):
    m, se = np.mean(data), sp.stats.sem(data)
    h = se*sp.stats.t.ppf((1+confidence)/2.,len(data)-1)
    return m, m-h, m+h
print('For data the mean  can also  be calcaleted as at 95% confidence level is :', mean_confidence_interval(b, 0.95))


a complete ploted distribution of confidence level on t mode

  import numpy as np
#  import seaborn as sns
  from scipy import stats
  import matplotlib.pyplot as plt

  np.random.seed(3)
  MU = 64
  sigma = 5
  size = 10
  heights = np.random.normal(MU, sigma,size)
  print("accoding to the mean and deviation we have a example of 10 rondom number : ", heights)

  mean_heights = np.mean(heights)
  deviation_heights = np.std(heights)
  SE = np.std(heights)/np.sqrt(size)

  print('99% confidence interval is :', stats.t.interval(0.99, df = size-1 , loc = mean_heights, scale=SE))
  print('90% confidence interval is :', stats.t.interval(0.90, df = size-1 , loc = mean_heights, scale=SE))
  print('80% confidence interval is :', stats.t.interval(0.80, df = size-1 , loc = mean_heights, scale=SE)) 

a complete ploted distribution

import numpy as np

sample_size = 1000
heights = np.random.normal(MU, sigma, sample_size)
SE = np.std(heights)/np.sqrt(sample_size)
(l,u) = stats.norm.interval(0.95, loc = np.mean(heights), scale = SE)
print(l,u)
plt.hist(heights, bins = 20)
y_height = 5
plt.plot([l,u], [y_height, y_height], '_', color='r')
plt.plot(np.mean(heights), y_height, 'o', color= 'b')
plt.show()

a complete ploted distribution on between region

x = np.linspace(-5,5,100)
y = stats.norm.pdf(x,0,1)
plt.plot(x,y)
plt.vlines(-1.96,0,1,colors='r',linestyles='dashed')
plt.vlines(1.96,0,1,colors='r',linestyles='dashed')
fill_x = np.linspace(-1.96,1.96,500)
fill_y = stats.norm.pdf(fill_x, 0,1)
plt.fill_between(fill_x,fill_y)
plt.show()

a example from internet

import pandas as pd
from scipy import stats as ss
data_url = "https://raw.githubusercontent.com/alstat/Analysis-with-Programming/master/2014/Python/Numerical-Descriptions-of-the-Data/data.csv"
df = pd.read_csv(data_url)
print(df.describe())
import matplotlib.pyplot as plt
pd.options.display.mpl_style = 'default' 
plt.show(df.plot(kind = 'box'))

1 2 3 order and gauss fitting

import numpy as np
import matplotlib.pyplot as plt
from scipy import optimize
from scipy.optimize import curve_fit


def f_1_degree(x,A,B):
    return A*x + B

def f_2_degree(x,A,B,C):
    return A*x**2 + B*x + C

def f_3_degree(x,A,B,C,D):
    return A*x**3 + B*x**2 + C*x + D


def f_gauss(x,A,B,sigma):
    return A*np.exp(-(x-B)**2/(2*sigma**2))

def plot_figure():
    plt.figure()

    x0 = [1,2,3,4,5]
    y0 = [1,3,8,18,36]

    #plot original data
    plt.scatter(x0,y0,25,"red")

    # plot f1
    params_1, pcovariance_1 = optimize.curve_fit(f_1_degree,x0,y0)

    params_f_1, pcovariance_f_1 = curve_fit(f_1_degree,x0,y0)
    x1 = np.arange(0,6,0.01)
    y1 = params_1[0]*x1+params_1[1]
    plt.plot(x1,y1,"blue")
    print("The liear fitting for date is : y = ",params_1[1],"*x + ",params_1[0])
    print("The params uncertainies are:")
    print("a =", params_1[0], "+/-", round(pcovariance_1[0,0]**0.5,3))
    print("b =", params_1[1], "+/-", round(pcovariance_1[1,1]**0.5,3))


    #plot f2
    params_2, pcovariance_2 = curve_fit(f_2_degree,x0,y0)
    x2 = np.arange(0,6,0.01)
    y2 = params_2[0]*x1**2+params_2[1]*x1 + params_2[2]
    plt.plot(x2,y2,"green")
    print("The second order curve fitting for date is : y = " ,params_2[2],"*x² + " ,params_2[1],"*x + ",params_2[0])
    print("The params uncertainies are:")
    print("a =", params_2[0], "+/-", round(pcovariance_2[0,0]**0.5,3))
    print("a =", params_2[0], "+/-", round(pcovariance_2[0,0]**0.5,3))
    print("b =", params_2[1], "+/-", round(pcovariance_2[1,1]**0.5,3))
    print("c =", params_2[2], "+/-", round(pcovariance_2[2,2]**0.5,3))

    #plot f3
    params_3, pcovariance_3 = curve_fit(f_3_degree,x0,y0)
    x3 = np.arange(0,6,0.01)
    y3 = params_3[0]*x1**3+params_3[1]*x1**2 + params_3[2]*x1 + params_3[3]
    plt.plot(x3,y3,"purple")
    print("The second order curve fitting for date is:y =",params_3[3],"*x³+",params_2[2],"*x² + " ,params_2[1],"*x + ",params_2[0])
    print("The params uncertainies are:")
    print("a =", params_3[0], "+/-", round(pcovariance_3[0,0]**0.5,3))
    print("b =", params_3[1], "+/-", round(pcovariance_3[1,1]**0.5,3))
    print("c =", params_3[2], "+/-", round(pcovariance_3[2,2]**0.5,3))
    print("d =", params_3[3], "+/-", round(pcovariance_3[3,3]**0.5,3))

    #plot gauss
    params_gauss, pcovariance_gauss = curve_fit(f_gauss,x0,y0)
    xgauss = np.arange(0,6,0.01)
    ygauss = params_gauss[0]*np.exp(-(xgauss-params_gauss[1])**2/(2*params_gauss[2]**2))
    plt.plot(xgauss,ygauss,"black")
    print("The gauss function curve fitting for date is : y = ",params_gauss[2],"*exp{-(x-",params_gauss[1],")²/(2*sigma²) +",params_gauss[0])
    print("The params uncertainies are:")
    print("a =", params_gauss[0], "+/-", round(pcovariance_gauss[0,0]**0.5,3))
    print("mean =", params_gauss[1], "+/-", round(pcovariance_gauss[1,1]**0.5,3))
    print("std =", params_gauss[2], "+/-", round(pcovariance_gauss[2,2]**0.5,3))



    plt.title("plot for different fittign")
    plt.xlabel("x")
    plt.ylabel("y")
    plt.show()
    return

plot_figure()


linear fitting

# matplotlib inline
import matplotlib.pyplot as plt;
import numpy as np;
from scipy import integrate
from scipy.optimize import curve_fit
import math

#1. x axis coordinnat for 10 points data
xmin=0.01; xmax=2; pts = 10;
xx = np.linspace(xmin, xmax, pts);

#2. y axis coordinnat for 10 points data
rho = np.sqrt(1/xx) + 0.5*np.exp(xx)*xx**2;

#plot the original data
plt.plot(xx, rho, 'bo', label='Original data')

#3. x axis coordinnat for 200 points fitting
x_fine = np.linspace(xmin, xmax, 200);

#fiting
params, cov = np.polyfit(xx, rho, 1, cov=True)

#to reconstruct the linear function
bestfit_rho = params[0]*x_fine + params[1]
plt.plot(x_fine, bestfit_rho, 'r-', lw=2, label='One order of linear fit');

print(params)



linear fitting with ployfit

# matplotlib inline
import matplotlib.pyplot as plt;
import numpy as np;
from scipy import integrate
from scipy.optimize import curve_fit
import math

#1. x axis coordinnat for 10 points data
xmin=0.01; xmax=2; pts = 10;
xx = np.linspace(xmin, xmax, pts);

#2. y axis coordinnat for 10 points data
rho = np.sqrt(1/xx) + 0.5*np.exp(xx)*xx**2;

#plot the original data
plt.plot(xx, rho, 'bo', label='Original data')

#3. x axis coordinnat for 200 points fitting
x_fine = np.linspace(xmin, xmax, 200);

#fiting  it can be any order 
params, cov = np.polyfit(xx, rho, 4, cov=True);
p = np.poly1d(params)
plt.plot(x_fine, p(x_fine), 'g-', lw=2, label='The Best poly1d fit');

print(params)
plt.xlabel('$x$');
plt.ylabel(r'$\rho$');
plt.legend(fontsize=13);
plt.show()


High performance Data Analysis lecture

concepts

High performance Data Analysis: with parallel processing to quickly find the insights from extremely large data sets

Chap01 overview

Distributed System

  1. Definiation:
  • Components separate located
  • communicatation through passing massage between components
  1. Characteristics:
  • own memory
  • concurrency
  • locks
  1. Applcation:
  • cloud compuation
  • internet of Things
  1. Algorithm:

Consensus, Repication

  1. Challages:
  • Programm
  • resource sharing

Levels of parallelism

Bit-level, Instruction level, Data level, Task level

Name typical applications for high-performance data analytics

  1. weather forecast
  2. Simulating kernel fusion, tokamak reactor

Distinguish HPDA from D/P/S computing and how these topics blend

Stricter than distributed system( strongly scalling: weak scalling)

Describe use-cases and challenges in the domain of D/P/S computing

Recommendation engine

Describe how the scientific method relies on D/P/S computing

Simulation models real systems to gain new insight Big Data Analytics extracts insight from data

Name big data challenges and the typical workflow

how to deal with big data(5Vs) Raw-> Descriptive -> Diagnostics -> Predictive -> Prescriptive

Recite system characteristics for distributed/parallel/computational science

Sketch generic D/P system architectures

Chap02 DataModels & Data Processing Strategies

Define important terminology for data handling and data processing

Raw data, semantic normalization, Data management plan, Data life cycle, data governance, data provenance...

Sketch the ETL process used in data warehouses

extract from a source database, transform with controlling, error and missing treatment, change the layout to fit loading, integrate them into data warehouses for user

Sketch a typical HPDA data analysis workflow

classical: discovery, integration, exploitation in high level, with SQL, java, scala, Python, with parallelism for data Exploration

Sketch the lambda architecture

Lambda architecture is a concept for enabling real-time processing and batch methods together. batch layer(large scala) + serving layer speed layer(read time)

Construct suitable data models for a given use-case and discuss their pro/cons

Define relevant semantics for data

data models

Concurrency, Durability, Consensus,

  • relational model
  • Clumnar Model (combinded relational model)(HBase)
  • key-value model (BigTable)
  • Documents model (MongoDB)
  • Graph

Chap03 Databases and DataWarehouses

relatation model

  1. Cardinality

    • one to one
    • one to many
    • many to many
  2. Normalization Form

    reduces dependencies, prevents inconsistency, save space

    • 1NF: no collections in row tuples
    • 2NF: no redundancy (entities of many-to-many relations are stored in separate tables)
    • 3NF: no dependence between columns
    • 4NF: no multiplie relationships in one table(not good for big data)
  3. group by

    it's done with Aggregatation(in sql or in python, both)

  4. join

    cross join: Cartesian product of two tables natural jon: all combinations that are equal on their common attributes inner join: only all condition satisfied left join: condition strict on left right join: condition strict on right full join

  5. Transactions

    ACID

Define Database, DBMS, and Data Warehouse

  • an organized collection of data
  • software application for user to use the collected data
  • a system used for reporting and data analysis, with multidimensional data cube

Create a relational model for a given problem

Draw an ER(Entity Relational) diagram for a given relational model (and vice versa)

Normalize a small relational model into a redundant-free model

List the result of an inner join of two tables to resolve relationships

Formulate SQL queries for a relational model

Create a Star-Schema from a relational model (and formulate queries)

Sketch the operations for an OLAP cube

  • Slice
  • Dice
  • Roll up
  • Pivot

Appraise the pro/cons of OLAP vs. traditional relational model

Star-Schema: pro: simplification of query and performancd gain, emulates OLAP cube start-Schema: cons: data integrity is not guaranteed, no natural support of many to many relations,

Describe DBMS optimizations: index, bulk loading, garbage cleaning

Chap04 Distributed Storage and Processing with Hadoop

hadoop

map: filter and convert all input into key-value tuples reduce: receives all tuples with the same keys, accumulated

Describe the architecture and features of Apache Hadoop

  • HDFS and MapReduce executation engine
  • High availability,
  • automatic recovery
  • Replication of data
  • Parallel file access
  • Hierarchical namespace
  • Rack-awareness

Formulate simple algorithms using the MapReduce programming model

Justify architectural decisions made in Apache Hadoop

Sketch the execution phases of MapReduce and describe their behavior

  1. distributed code
  2. determine fiels
  3. map
  4. combine
  5. shuffle
  6. partition
  7. reduce
  8. output

Describe limitations of Hadoop1 and the benefits of Hadoop2 with TEZ

  • Allow modelling and execution of data processing logic
  • Reconfigure dataflow graph based on data sizes and target load
  • Controlled by vertex management modules
  • Task and resource aware scheduling
  • Pre-launch and re-use containers and caching intermediate results
  • Everyone has to wait for the prozess between mapping and reducing

Sketch the parallel file access performed by MapReduce jobs

Chap05 Big Data SQL using Hive

Compare the execution model of SQL in an RDBMS with Hive

  • Table: Like in relational databases with a schema
  • Partitions: table key determining the mapping to directories
  • Buckets/Clusters: Data of partitions are mapped into files

Justify the features of the ORC format(Optimized Row Columnar)

  • Light-weight index stored within the file
  • Compression based on data type
  • Concurrent reads of the same file
  • Split files without scanning for markers
  • Support for adding/removal of fields
  • Partial support of table updates
  • Partial ACID support (if requested by users)

Apply a bloom filter on example data

Identify if an element is a member of a set with n elements Allow false positives but not false negatives

Describe how tables are generally mapped to the file system hierarchy and optimizations

Describe how data sampling can be optimizing via the mapping of tables on HDFS

Sketch the mapping of a (simple) SQL query to a MapReduce job

Chap06

Create a Columnar Data Model (for HBase) for a given use case

Justify the reasons and implications behind the HBase storage format

  • medium-size object,

  • stored by row key,

  • cell data is kept in store files on HDFS,

  • Encoding can optimize storage space

    • row keys and date
    • column family
    • Reading data

Describe how HBase interacts with Hive and Hadoop

Describe the features and namespace handling in Zookeeper

Create a Document Data Model (for MongDB) for a given use case

Provide example data (JSON) for the MongoDB data model and the queries

Sketch the mapping of keys to servers in MongoDB and HBase

Select and justify a suitable shard key for a simple use case

Chap07

Define in-memory processing

Processing of data stored in memory

  • Data will fit in memory
  • Additional persistency is required
  • Fault-tolerance is mandatory

Describe the basic data model of Apache Spark and the SQL extension

it based on RDDs, which are immutable tuples, (Resilient Distributed Datasets) Computation is programmed by transformation, lazy evaluation, all computaion is deferred until needed by actions

Program a simple data flow algorithm using Spark RDDs

nums = sc.parallelize(arange(1,100000)) r1 = nums.filter(lambda x: (x%2) == 1) r1 = r1.map(lambda x:(x, x**2)) r1. = r1.reduce(lambda a,b :a * b)

Sketch the architecture of Spark and the roles of its components

  • Transformation: map, filter, union, pipe, groupbykey, join
  • Actions: reduct, count, token, frist
  • Schuffle: repartation

Describe the execution of a simple program on the Spark architecture

Chap08

Define stream processing and its basic concepts

Application for real-time continuous stream-computation for high-velocity data Stream groupings defines how tuples are transferred

Describe the parallel execution of a Storm topology

the graph of the calculation represented as network, the parallelism (tasks) is statically defined for a topology

Illustrate how the at-least-once processing semantics is achieved via tuple tracking

one tuple may be executed multiple time, and if error occurs, tuple restarted from Spout

  • each tuple has a tuple ID
  • Acker tracks tuple ID with hashing map
  • Ack execute each step with XOR of all derived tuple ID, if it retures value 0, retart from Spout agin

Describe alternatives for obtaining exactly-once semantics and their challenges

  • each tuple is executed exactly once,
  • provide idempotent operations
  • Execute tuples strongly ordered to avoid replicated execution
  • Use Storm's transactional topology(processing phase, commit phase[stong ordering])

Sketch how a data flow could be parallelized and distributed across CPU nodes on an example

Chap09

Chap10

List example problems for distributed systems

Reliable broadcast, Atomic commit, Consensus, Leader election, Replication

Sketch the algorithms for two-phase commit

Prepare phase, Commit phase

consistent hashing

manage the key/value data in distributed system load balancing, and faul tolerant

Discuss semantics when designing distributed systems

Consistency(atomicity, visibility, isolation) Availability(Robustness, Scalability, Partition) Durability

Discuss limitations when designing distributed systems

CAP(Consistency, Available, Partition tolerance) can't meet together in a DS

Explain the meaning of the CAP-theorem

Sketch the 3-tier architecture

Presentation, Application precessing, Data management

Design systems using the RESTful architecture

Simplicity of the interface, Portability, Cachable, Tracable

Describing relevant performance factors for HPDA

Time, cost, energie, Productivity

Listing peak performance of relevant components

Computation, Communicatation, Input/Output devices

Assessing /Judging observed application performance

  • Estimate the workload
  • Compute the workload throughout per node, W
  • Compute the Hardware capabilities P

E = W / P

Chap11

Sketching the visual analytics workflow

Listing optical illusions

Color, Size&Shape, Moving,Interpretation of objects,

Listing 5 goals of graphical displays

  • show the data
  • induce the viewer to think about the substance
  • present many numbers in a small space
  • make large data sets coherent
  • serve a reasonably clear purpose
  • be closely integrated with the statistical

Discuss the 4 guidelines for designing graphics on examples

  • Use the right visualization for data types
  • Use building blocks for graphics (known plot styles)
  • Reduce information to the essential part to be communicated
  • Consistent use of building blocks and themes (retinal properties)

Describe the challenges when analyzing data

  • large data volumes and velocities
  • complex system and storage topologies
  • understand the system behavior is difficult
  • data movement of memory and CPU is costly

Discuss the benefit of in-situ and in-transit data analysis

  • in-situ: analyze results while the applications is still running
  • in-transit: analyze data while it is on the IO path
  • interact with application while it runs

Chap12

Sketch a typical I/O stack

Develop a NetCDF data model for a given use case

Compare the performance of different storage media

Sketch application types and access patterns

Justify the use for I/O benchmarks

Can use simple/understandable sequence of operations May use a pattern like a realistic workloads Sometimes only possibility to understand hardware capabilities

Describe an I/O performance optimization technique

Read-ahead, write-behind, async-IO

Describe a strategy for trustworthy benchmark result

single-shot: acceptance test periodically: regression test

03-01

drop table if exists WikipediaArticles ;
create table WikipediaArticles (
id int,
title varchar(50), 
text varchar(50),
category varchar(50),
link int
) ;
\d wikipediaarticles;
drop table if exists linkarticles ;
    create table linkarticles (
    id int,
    linked int
 ) ;
delete from wikipediaarticles where id = 1;
insert into WikipediaArticles (id, title, text, category, link) values (1, 'math', 'mathematics and nature and nature', 'nature', 1) ;
delete from wikipediaarticles where id = 2;
insert into WikipediaArticles (id, title, text, category, link) values (2, 'phy', 'physics', 'nature', 2) ;
delete from wikipediaarticles where id = 3;
insert into WikipediaArticles (id, title, text, category, link) values (3, 'chemie', 'chemistry', 'science', 3) ;
delete from wikipediaarticles where id = 4;
insert into WikipediaArticles (id, title, text, category, link) values (4, 'bio', 'biology', 'science', 4) ;
select * from wikipediaarticles ;
delete from linkarticles where id = 1;
insert into Linkarticles (id, linked) values (1, 2) ;
insert into Linkarticles (id, linked) values (1, 3) ;
delete from linkarticles where id = 2;
insert into Linkarticles (id, linked) values (2, 3) ;
delete from linkarticles where id = 3;
insert into Linkarticles (id, linked) values (3, 4) ;
delete from linkarticles where id = 4;
insert into Linkarticles (id, linked) values (4, 1) ;
select * from linkarticles ;
select * from wikipediaarticles where title = 'phy';
select * from wikipediaarticles where id in
 (select linked from linkarticles where id in
  (select id from wikipediaarticles where title = 'math')
);

select count(*) , linked from linkarticles group by linked;
select unnest(string_to_array('this is is is a test', ' '))
select id,  unnest(string_to_array(text , ' ')) as word, count(*) from WikipediaArticles group by id, word
select * from wikipediaarticles where category = 'science';

03-02

digraph diagramm {
  WikipediaArticles  -> id
  WikipediaArticles  -> Title
  WikipediaArticles  -> Text
  WikipediaArticles  -> Category
  WikipediaArticles  -> Links
  Links  -> linkarticles
  linkarticles -> lid
  linkarticles -> linked
}

04-01

mapper and reducer in own

def mapper(key, value):
  words = key.split()
  for word in words:
    Wmr.emit(word, 1)

def mapper(key, value):
  words = key.split()
  for word in words:
    Wmr.emit("s", stem(word), 1)
  for word in words:
    Wmr.emit("l", lemmatize(word), 1)


def reducer(key, values):
  count = 0
  for value in values:
    count += int(value)
    Wmr.emit(key, count)

sql

cat ~/Documents/hpda0404.csv 
drop table if exists hpda0401 ;

create table hpda0401 (
num int,
germany varchar(10),
english varchar(10),
chinese varchar(10),
listed int
) ;

insert into hpda0401 (num, germany, english, chinese, listed) values (1, 'eins', 'one','一', 1);
insert into hpda0401 (num, germany, english, chinese, listed) values (2, 'zwei', 'two','二', 1);
insert into hpda0401 (num, germany, english, chinese, listed) values (3, 'drei', 'three','三', 2);
insert into hpda0401 (num, germany, english, chinese, listed) values (6, 'sechs', 'six','六', 2);

select germany from hpda0401 where  germany = 'zwei';

select listed, sum(num) as mysum from hpda0401 group by listed;

select

import csv
from functools import reduce
path = "/home/si/Documents/hpda0404.csv"
data = []
with open(path) as f:
    records = csv.DictReader(f)
    for row in records:
        data.append(row)
    print(data)


mapiter = map(lambda x: x["germany"], data)
maplist = [ele for ele in mapiter]
print(maplist)    

filteriter = filter(lambda x: x=="zwei", maplist)
filterlist = [ele for ele in filteriter]
print("select germany WHERE germany == zwei :", filterlist)

summation

import csv
from functools import reduce
path = "/home/si/Documents/hpda0404.csv"
data = []
with open(path) as f:
    records = csv.DictReader(f)
    for row in records:
        data.append(row)
    print(data)


iters = map(lambda x: x["listed"], data)
iterslist = [ele for ele in iters]
iterset = set(iterslist)
print("grouped by ", iterset)

dic = {}
for i in iterset:
    temp = []
    for d in data:
        for (j, n) in [b for b in map(lambda x: (x["listed"],x["num"]), [d])]:
            if i == j:
                temp.append(int(n))
    reduer = reduce(lambda x, y:x+y, temp)
    dic[i]= reduer

print("sum (num) GROUP) BY listed : ", dic)

join

cat ~/Documents/hpda0404a.csv 
cat ~/Documents/hpda0404b.csv
import csv
from functools import reduce
path1 = "/home/si/Documents/hpda0404a.csv"
path2 = "/home/si/Documents/hpda0404b.csv"
data1 = []
with open(path1) as f:
    records = csv.DictReader(f)
    for row in records:
        data1.append(row)
    print(data1)

data2 = []
with open(path2) as f:
    records = csv.DictReader(f)
    for row in records:
        data2.append(row)
    print(data2)    


for a in data1:
    aid = [y for y in map(lambda x: x["id"], [a])]
    for b in data2:
        bid = [y for y in map(lambda x: x["id"], [b])]
        if aid == bid:
            (af1, bf2) = ([y for y in map(lambda x: x["germany"], [a])], [y for y in map(lambda x: x["fan"], [b])])
            print(af1, bf2)

04-02

2.1

from nltk.stem.snowball import SnowballStemmer
from nltk.stem import WordNetLemmatizer

stemmer = SnowballStemmer("english")
lemmatizer = WordNetLemmatizer()

file = "/home/si/Documents/hpda0402wordscount.txt"
sdict = {}
ldict = {}
with open(file, "r") as data:
    datas = data.read()
    words = datas.split(' ')
    for word in words:
        sword = stemmer.stem(word)
        lword = lemmatizer.lemmatize(word)
        if sword in sdict:
            sdict[sword] += 1
        else:
            sdict[sword] = 1

        if lword in ldict:
            ldict[lword] += 1
        else:
            ldict[lword] = 1

    print("---------sdict----------------------")
    for (item, key) in sdict.items():
          print(item, key)

    print("---------ldict----------------------")
    for (item, key) in sdict.items():
        print(item, key)


2.2

2.3

see in Document folder

2.4

mapper

import sys
for line in sys.stdin:
  words = line.strip().split(" ")
    for word in words:
    print(word + "\t" + "1")

reducer

import sys

oldword = ""
count = 0
for line in sys.stdin:
    (word, c) = line.strip().split("\t")
    if word != oldword:
        if count != 0:
            print(oldword +"\t"+ str(count))
        count = 0
        oldword = word
    count = count + int(c)
if oldword != "":
    print(oldword +"\t%d" %(count))
cd /home/hadoop/hadoop-3-3.1/sbin
./start-dfs.sh
./start-yarn.sh
jps

word count example

hdfs daf -put /home/si/Documents/hpda/hpda04-2.3.txt /
hadoop fs -rm -r /hpda04-2.3-output/
hadoop jar share/hadoop/mapreduce/hadoop-mapreduce-examples-3.3.1.jar wordcount /hpda04-2.3.txt /hpda04-2.3-output/
hadoop fs -cat /hpda04-2.3-output/part-r-00000
cd output
hadoop fs -getmerge /hpda04-2.3-output/ out

With errors

yarn jar share/hadoop/tools/lib/hadoop-streaming-3.3.1.jar -Dmapred.reduce.tasks=1 -Dmapred.map.tasks=11 --mapper /home/si/Documents/hpda/04/mapper.py -reducer /home/si/Documents/hpda/04/reducer.py -input /hpda04-2.3.txt --output /hpda04-2.3-output/

05

import csv

class dataflow:
    def __init__(self):
        self.data = []

    def read(filename):
        d = dataflow()
        with open(filename, newline='') as csvfile:
            spamreader = csv.reader(csvfile)
            for row in spamreader:
                d.data.append(row)
        return d

    def map(self, func):
        d = dataflow()
        for x in self.data:
            d.data.append(func(x))
        return d

    def filter(self, func):
        d = dataflow()
        for x in self.data:
            if func(x):
                d.data.append(x)
        return d

    def write(self, filename):
        d = dataflow()
        with open(filename, 'w', newline='') as csvfile:
            spamwriter = csv.writer(csvfile, quoting=csv.QUOTE_MINIMAL)
            for d in self.data:
                spamwriter.writerow(d)
        return d
    def __str__(self):
        return str(self.data)


d = dataflow.read("/home/si/Documents/hpda/05/file.csv")
print(d)
flat = d.map(lambda t: (t[0], eval(t[3])))
bd = flat.filter(lambda t: "HPDA" in t[1])
bd.write("/home/si/Documents/hpda/05/out.csv")

06

MongoDB

show dbs
use testdatabase
db.getCollectionNames()
use testdatabase;
db.wiki.drop();
db.createCollection("wiki");
show collections;
use testdatabase;
db.wiki.insert({_id:1, "person":"Gauss","Beruf":"Mathematiker" })
db.wiki.find()
use testdatabase;
db.wiki.update({"person":"Gauss"},{"Beruf": "Mathematiker Physiker" })
db.wiki.find()
use testdatabase;
db.wiki.update({"person":"Gauss"}, {"Beruf": "Mathematiker Physiker", "Wohnsite": "Göttingen Hannover"})
db.wiki.find()
use testdatabase;
db.wiki.drop()

Paralle compuation lecture

performance

Andel's law:

if the task is changed, Gostafan's law,

all is changed task, such as 70% task doubled, will be 1.4

Effectivy:

Chap1: introduction

Von Nroven

cpu, interconnection, memory

memory mode

shared memory distributed memory

shared memory

easy to build ,hard to large scare

distribution memory

Chap 2: Proformance

CPI: cycles per instruction MIPS: Million Instructions per second FLOPS: Floating Point Operation per second

Benchmark idle

Does this also mean in a hundred percent parallel code , the speed up is proportional to the number of threads?

  • Yes

fashion inductive

: The Time for task which can't be parallelized. : The Time for task which can be parallelized. : number of processes : Precent of Task, which can be parallelized

single Process:

speedup: . if the parallelized part are perfect parallelable, .

Multi processes

speedup: .

Efficient

Adaes-low

Gustafon low

Cloud computation lecture

Platform Virtualization

Defination of Virtualization

the processes of creating software-based version of resources.

The reasons for applying virtualization

  • Utilization: Server consolidation
  • Isolation: Implication of errors is restricted in virtual resource only
  • Flexiblity: many Application access the same physical Hardware
  • On-demand: virtual resource is created/destoryed on request
  • Migration: Fault tolerance, live update, optimization of performance
  • New reaserch:new OS new technology
  • Encapsulation: current stats can be saved copied and loaded
  • Minimal downtime
  • Fast provisioning

Full virtualization (Hypervisor system, Bare matal)

  • Translation of instructions
  • implantation: Virtual Box
  • Hypervisor receive the IO from application,and translate to HW
  • Hypervisor translate the request from Guest OS to HW
  • no need special HW support
  • no need modified OS

Hardware-assisted virtualization (Hypervisor system, Bare matal)

  • implantation: VMware Workstation
  • can install many virtual machine
  • need special HW support
  • no need modified OS

Para virtualization (Hypervisor system, Bare matal)

  • VM(modified OS) runs on Host

  • Host on hypervisor

  • implantation: linux kernel

  • need modified OS

  • need Host OS level on hypervisor

Host OS virtualization (Hypervisor system, Hosted)

  • Guest OS on Hypervisor
  • Hypervisor on Host OS
  • Host on HW
<!-- -->
  • no need modified OS
  • need Hypervisor on Host OS
  • inter VM communication is difficult

OS-level virtualization (Container system)

  • no hypervisor
  • multiple useer instances(light-weight) run on a host OS
  • implantation: Docker

Memory virtualization

  • shadow page table on Guest OS
  • Extended Page table in Host

Network virtualization

hypervisor provide virtual switch, offering every VM a ip address

Feathers


Encapsulation solation Hardware abstraction Migration Partation

Kubernetes

Container-Orchestration System

  • Cluster
  • Control Plane
  • Workload:application on Kubernetes
  • Pod: many containers share the same volume
  • Deployment
  • Service

Virtual Machine

  • Partition
  • Isolation
  • Encapsulation
  • Hardware abstraction
  • Live Migration

Storage Virtualization

SSD advantage and disadvanage over HDD

  • Reliablity

  • Fast

  • small Size

  • More expensive

  • less Space

Storage virtualization advantage

  • Faster access: because you can have multiple data sources for the same data
  • Independence of logic storage resources
  • improvement of management: Moving data easy, in multiple localaction
  • High reliablity: because of Redundancy
  • High effience: Replication and Duplication
  • compression, compaction
  • increasing volume if needed

Provisioning:

  • allocate disk space to user on demand
  • give a mount of Storage, but not really allocated so much

Deduplication

Single instance Storage: if the hash value of a datablock is the same with one we already stored, dann save its link

  • checksum with hash value

Compression:

compacting the data so that it comsumes less space

Cloning

Consuming no storage except what is required for metadata until changes are written to the copy

Snapshotting Copies

a read-only, point-in-time image of a volume

increasing the proformance

with more physical disks at the same time

Modern Datacenters

automation

  • scaling

  • Inreases Repeatablity

  • Make processes Faster

  • imporve Reliablity

  • disadvanage Additional Complexity illusion of Stability

Idempotent

the same code generate the same result, without any change

Infrastructure as code

  • Benefits:
    • Repeatablity
    • Agility
    • Disaster Recovery
    • fast deploy
    • live upgrade
  • Imperative:describe the stes to get to desired state
  • Declarative: describe the desired state

Foreman:

give the initial configuration to run an OS

Puppet

  • Declarative description of resource states
  • Client / server Architecture
  • Security throgh cettificate
  • OS abstraction

Monitor

challange

collecte data from large mount of servers Watch out the overhitting

Real time monitoring

  • Availability Monitoring: altering of failure
  • Capacity Monitoring: detect outages of resource

Historical Monitoring

  • Long-term information
  • Trend analysis
  • Capacity planning

Architecture

  • Measurement: Blackbox, Whitebot,Gauges, Conntes
  • Collection: push, pull
  • Analysis: real time, short term, long term, Anomaly detection with AI
  • Alerting:
  • Virtualization

Cloud Computing Concepts

Cloud Defination

Cloud Computing is a model for enabling on-demand network
access to a shared pool of configurable computing resource
(network, server, storage, application, service) that can
be rapidly provisioned and released with minimal management
effort or service provider interaction

SOA

Servive Oriented Architecture SOA has become a core concept of service computing and provides the fundamental technologies for realizing service computing

Advantage

  • No captial costs
  • High scalability
  • Highh Flexiblity

Network design

Different: SDN: software define Network New architectures have a detached control plane instead of heavy logic switching/routing in hardware

  • hardware independent
  • better shaping and Qos(Quit of service)
  • Data Center Briding for local and remote network

GWDG feathers

  • self service front-end
  • SSH authenticate
  • snapshotting
  • using Openstack

Infrastructure as Service

  1. Different deployment methode


    Private Cloud community Cloud public Cloud Hybird Cloud

  2. Storage

    CDMI: Cloud Data Management Interface File, Block Devices, Object Stores, Database Store example: AWS S3

  3. Network

  4. advantage

    • quick implement of new project
    • Flexiblity and scalability
    • no hardware costs
    • pay only what you need
  5. disadvantage

    • complicated to change provider
    • dependency on provider
    • internet access is essential

Platform as a Service

  • Rapid Time-to-Market
  • Minimal Development
  • Reduced Pressure on internal resources

Software as a Service

based on IaaS, fouce on Applications

Web services

Benefits

  • Programmable access
  • Distribution over internet
  • Encapsulation of discrete functionality
  • can offer stardartized Interface
    • TCP/IP prokotoll
    • HTTP based

SOAP

Simple Object Access Protocol xml based RPC based

WSDL

Web Services Description Language xml based

REST

  • Everything is resource

  • Every resource is identified by a unique Identifier

  • Using simple and uniform interface

  • Communication is done by representation

  • be stateless

  • more flexiblity

  • less redundancy, raw message based

  • URI and URL

API

Application Programming Interface

Big Data Service

feathers

  • Volume: Scale of data
  • Velocity : spend of transfer data
  • Variety: Different form of data
  • Veracity: Uncertainty of data

processes

  • Acquisition, Recording
  • Extraction, Cleaning, Annotation
  • Integration, Representation
  • Analysis, Modeling
  • Interpretation, Virtualization

Challenges

  • Heterogeneity, Incompleteness
  • Scale
  • Timeliness
  • Privacy

Mapreduce


map map the data into key-value-pairs according to our problem reduce key-value-pairs get accumlated shuffling


Large Scale Data Analysis

batch process

disadvanage: views generated in batch may out of date

steaming process

disadvanage: expensive and complex

Stream Computation Platform

  • Apache Storm
  • Spark Streaming
  • Apache Flink
  • Heron

Hadoop

HDFS

Namenode vs DataNodes

YARN

Resource Manager vs NodeManager

Apache Kafka

  • Fast, efficient IO
  • Fault tolerant storage
  • Publish and Subscribe to steams of records

Data management cycle

  • Data
  • Meta-data
  • PID
  • Search
  • Disposition

Data Grid Data Management

Data Lake

A data lake is a data storage, where raw data can be stored, whos structure is determined at the extraction from the lake

  1. Challenges

    • Reliablity
    • Slow Performance
    • Lack of security
  2. Zones

    • Transient
    • raw
    • trusted
    • refined

ETL

Extract transform load

Storage data in Multiable locations

Redundancy for high-availability because of server falied and fast access of data

Storage data in remote data center

it is harder to acidentally delete something, such as because of disaster.

code storage

ssd

fair data management

Find-able Accessable Interoperable Reproducible

ITIL &SLA

non functional service

organizational Operation of server server quality like availability usability

server value value co-creation IT service Management IT service Provider

ITIL Information Technology Infrastructure Library

a framework of best practices of IT service management and delivering

  1. service value system SVS

    1. Guiding principles

      • focus on value
      • start where you are
      • progress iteratively with feedback
      • collaborate and promote visibility
      • think and work holistically
      • keep in simple and practical
      • optimize and automate
    2. Service Value Chain

      • plan
      • improve
      • engage
      • design
      • transition
      • obtain
      • deliver
    3. ITIL Practices

  2. the four dimensions model

    Organization&People Information & Technology Value streams&Processes Partners&suppliers

SLA Service Level Agreement Life cycle

  • Development
  • Negotiation
  • Implementation
  • Execution
  • Assessment
  • Termination

SLA components include

  • Parties, terms, conditions
  • service defination include costs
  • Performance parameters
  • what is measured, how and when(monitoring)
  • what is done to in case a SLA is voilated

Security

Confidentiality

The ability to hide the information from the unauthorized people

Integrity

The ability to ensure that data are unchanged and remain a correct representation of original data

Availablity

data is available to authorized people

Asymmetric Encrytion RSA

Meassage: M
Content: N
Ciphertext: C
Public key: E
Encryption: E(x)
private key: D
Decryption: D(x)

RSA Algorithm
1. Select two prime number, p[13] and q[17]
2. Generate Algorithm content N[221]: N = q*p
3. calcalete the Eular function [192]: <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord mathnormal">φ</span><span class="mopen">(</span><span class="mord mathnormal" style="margin-right:0.10903em;">N</span><span class="mclose">)</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">=</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mopen">(</span><span class="mord mathnormal">p</span><span class="mspace" style="margin-right:0.2222em;"></span><span class="mbin">−</span><span class="mspace" style="margin-right:0.2222em;"></span></span><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord">1</span><span class="mclose">)</span><span class="mspace" style="margin-right:0.2222em;"></span><span class="mbin">∗</span><span class="mspace" style="margin-right:0.2222em;"></span></span><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mopen">(</span><span class="mord mathnormal" style="margin-right:0.03588em;">q</span><span class="mspace" style="margin-right:0.2222em;"></span><span class="mbin">−</span><span class="mspace" style="margin-right:0.2222em;"></span></span><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord">1</span><span class="mclose">)</span></span></span></span>
4. Rondomly generate public key e[5]: and e is relatively prime with <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord mathnormal">φ</span><span class="mopen">(</span><span class="mord mathnormal" style="margin-right:0.10903em;">N</span><span class="mclose">)</span></span></span></span>
5. calcalete the private key d[77]: so that <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.4653em;"></span><span class="mord mathnormal">e</span><span class="mspace" style="margin-right:0.2222em;"></span><span class="mbin">∗</span><span class="mspace" style="margin-right:0.2222em;"></span></span><span class="base"><span class="strut" style="height:0.6944em;"></span><span class="mord mathnormal">d</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">=</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:0.6444em;"></span><span class="mord">1</span></span></span></span>  mod <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord mathnormal">φ</span><span class="mopen">(</span><span class="mord mathnormal" style="margin-right:0.10903em;">N</span><span class="mclose">)</span></span></span></span>
6. pack Public key E = (n, e) and publish to someone
7. save Private key D =(n, d) 

Someone want to some me Mesaage M: [12]
Encryption: <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6833em;"></span><span class="mord mathnormal" style="margin-right:0.07153em;">C</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">=</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:0.6833em;"></span><span class="mord"><span class="mord mathnormal" style="margin-right:0.10903em;">M</span><span class="msupsub"><span class="vlist-t"><span class="vlist-r"><span class="vlist" style="height:0.6644em;"><span style="top:-3.063em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mathnormal mtight">e</span></span></span></span></span></span></span></span></span></span></span></span> mod n  [207]
send C [207] to me 

I do the Decryption
Message M: <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6833em;"></span><span class="mord mathnormal" style="margin-right:0.10903em;">M</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">=</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:0.8491em;"></span><span class="mord"><span class="mord mathnormal" style="margin-right:0.07153em;">C</span><span class="msupsub"><span class="vlist-t"><span class="vlist-r"><span class="vlist" style="height:0.8491em;"><span style="top:-3.063em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mathnormal mtight">d</span></span></span></span></span></span></span></span></span></span></span></span> mod n  [207**77%221]
get the Mesaage [12]

security benefits

  • Integrity
  • authentify the sender
  • non deniable for message

symmetric encryption

  • challange of key exchange
  • en/decryption with the same key

asymmetic encryption

  • en/decryption need more resource
  • safe key exchange

Digital Signiture

It's a certificate to identify the sender of message

how Certificate is trusted

OS deliver a list of already trusted accepted CAs, it's preconfigured

Authentication

verifies you are who you say you are

Authorization

verifies if you have the permission to access data

Confusion and Diffusion

confusion is to create faint ciphertexts in crytoprahic Diffusion, if one place of plain text the modified, many places can be modified


title: DAMA

#+STARTUP: overview

DAMA

Motivation for Data Management

  • Visibility
  • Reliability
  • Security
  • Scalability

challenges

  • reduce cost
  • increase storage
  • deliver stream data for more IoT

Motivation for Research Data Management

  • the amonut of data growth fast
  • new technologies
  • more accessible data due to standardisation
  • Required by funding agency
  • Scientific

Key difference between Data management Vs Data Science

  • Acquisition
  • Storage
  • Quality
  • Governance
  • Integrity

Data Science Life Cycle

Acquirement, clean, explore, preprocessing, model, validation, present

Research Data Life Cycle

Plan, Collect, Assure, Describe, Submit, Preserve, Discover, Integrate, Analysis, Publish

Research Data Life Cycle 2

Analysis <- discovery Archiving processing -> Distribution

  • version controll
  • provenance
  • normalization
  • integrity preservation
  • curation

Storage & Preseveration

  • storage, mid-term, on my own disk
  • preseveration, long term, accessible for other
  • 321
  • Accessibility, Authenticity, Longevity

Data Model

model

  • why? to save the data in the database or information system, conceptual representation of data objects, associcated with other data object
  • benefits, helpful for visual representation, busisses rules, regulatory compliances, consistancy conventions

data moduling technologies

  • ERM, Entity Relation Model
  • UML, Unified Modeling Language

Data modul Types

  • Conceptual
  • Logical
  • Physical

Data Type

Structured

Semi-Structured

self-describing structur json, XML, Email, Key-value-Store

Unstuctured

Data Acquire

  • Harvesting from external into system storage

  • Ingesting from different storages to different step for processing

Database

Hierarchical database

  • hierarchical structured
  • 1 to 1, 1 to n,
  • XML

Network database

  • Predecessor of relational database
  • more than one parent
  • allow n to n
  • uses a direct graph with direct link
  • can becomes a complex structure

Relational Database

  • not sufficient for fast growth of big data and its complexity
  • hard to scale horizontally
  • Normalization, reduce the disk space
  • DeNormalization, fast and optimised for query
  • Snowflake schema,
    • less disk space
    • normalized
    • minimal redundency
    • powerful for data analysis
    • allow many to many relationship
  • Star Schema(denormalization)
    • simple to understand and build
    • fast querying, no join

Object-Oriented Database

No-SQL database

  • for big data

ACID compliance

  • potential failures, server, power, OS
  • Atomicity
  • Consistency
  • Isolation
  • durablity IMB Statement

CAP Theorem

  • Consistency
  • Availability
  • Partition tolerance
  • sql(CAx), no-sql(xAP)

ETL Process

  • E, Extract: Read data from source
  • L, Load, store data in the final data store
  • T, Transform: modify data based on the requirement
  • mostly is ELT
  • but if the data source allow modification, TEL is also possible

Data Warehouse

  • integrated data from different source
  • resructure data (denormalization)
  • optimized for analysis
  • Building
    • Data source Layer: integrate internal and external data
    • Staging layer: conduct transformation
    • Storage Layer: host a database

Dagtabase

  • real time data
  • optimized for modification and querying(very efficient)
  • normalized data

Data access in system

  • OLTP: Normalized
  • OLAP: Denormalized

Data Marts

  • subject-oriented database
  • to meet the specific group of users
  • data access with higher performance
  • Data maintenance, different department can have their own controll
  • Easy setup, simple design, required less technical
  • Analysis, KPIs,
  • Easy input

Data Lake


data Warehouse Data Lake processed raw structured all possible and raw ready for analysis open business user data scientists costly easy more secure less sql no sql fast result slow resulte


Data Mesh

  • domain-oriented decentralized data owership and architecture
  • data as a product
  • self-serve data infrastructure as platform
  • federated computational governance
  • architecture for data governance

Data Fabric

  • conceptual
  • focus on highly automating and integrating
  • need more matedata

Meta Data

Meta data is must, a connect(descripation) data of data, necessary for control and efficiency while processing data, also important and required for access and discovery. problem, stored in different place also different form.

FAIR Principes

  • Findable
  • Accessable
  • interoperable
  • Reuseable
  • The principles emphasise machine-actionability, because humans increasingly rely on computational support to deal with data as a result of the increase in volume, complexity, and creation speed of data.

Type

direction

  • who created it, what it is, when, where, how, licence.

Meaning

  • Controlled Vocabular
    • list of words, to tag the information
    • predefined and authorized
    • reduce ambiguities of natural language
    • improve retrievablilty
    • support interoperable
  • Texonomies
    • with hierarchical structur
  • Thesaui
    • control of terms
    • Hierarchical, Equivalence, Association relationship within terms
    • support consistent indexing
    • serve interoperability
  • Ontologies, large Thesaui

Linked Data

  • URIs (Uniform Resource Identifiers) to name individual things
  • HTTP URIs to find things in web
  • linked data 2, all conceptual things should start with http

Signposting

An approach to make the scholarly web more friendly to machines.

PIDs

standard, invariant and long-term reference of a digital resource, regardless of status location or current owner

Actionable IDs

A Persistent Identifier (PID) policy for the European Open Science Cloud

Machine Actionable

means that a formal statement is syntactically and semantically specified enabling computing systems to carry out automatic processing.

URLS

  • subset of URIs
  • related to IP address

Sustainability by technology

  • reliable
  • robust
  • long term perspective

PID data type

Types are Metadata Elements

Data Governance

define

  • Data governance determines what the data represents and what it can be used for
  • Authentication and Authorization required

dimensions

  • Organization, roles, responsibilites(RACI model)
  • Process,
  • Technology
  • People, Trust, Ethics
  • Data

Role

  • Formed
  • Accountable
  • Consulted
  • Responsiable

Data Quality

  • Data quality describes how good it fits for its intended use: Operations, Decision making, Planning, Researching

Dimension

  • accessibility or availability
  • accuracy or correctness
  • comparability
  • completeness or comprehensiveness
  • consistency, coherence, or clarity
    • refers to whether the same data kept at different places do or do not match.
    • ACID ensure from one valid to another
    • peer-2-peer may be violated
  • credibility, reliability, or reputation
  • flexibility
  • plausibility
  • relevance, pertinence, or usefulness
  • timeliness or latency
  • uniqueness
  • validity or reasonableness

Data Management(DAMA)

Dimension is defined as a measurable features of an object

  • Accuracy
  • Availability
  • Clarity
  • Completeness

Data Security

Definition, planning, development, and execution of security policies and procedures to provide proper authentication, authorization, access, and auditing of data and information assets.

Access

  • role based access control
  • attribute-based access control

GraphQL

It's smart API, query intersting data in a smart way

Microservice Architecture

Api for difference Applications, also standardized

Function as a service

S3 Amazon

Data Operation

to improve the terms of time for data analysis

Data Flow Diagram

representing the flow of data through a process or system

Rules

  • a process must have at least one input data and one output data
  • data stroe must have at least one data flow in and data flow out
  • data stroage must through a process
  • all prcesses will go to another process or end up with data store
  • data can not flow between entities

event dirven Data handing

  • Synchronous
  • Asynchronous

Message Queue

  • producer/consumer
  • Eventual consistency / strong consistency(consistency)
  • At-least-once/Exactly-once/At-most-once(Processing models)

Read-only Data store

Principles

  • they are immutable
  • only original data source can deliver to RDS
  • one RDS for each application
  • each are specific applications
  • hosting near the original data
  • data provider is responsible for data integrity

title: Math

#+startup:  content

Statistic

Gauss distribution

标准高斯分布的积分包含了高斯积分

Co-variance matrix 协方差矩阵

<<covariance matrix link for ML>> for i = {1...n}, is a random variable, which belong to Gaussian distribution

set

co-variance matrix

\begin{equation}
\Sigma = 
  \left(
  \begin{array}{c}
          x_{1}-\bar{x}_{1} \\
          x_{2}-\bar{x}_{2} \\
          x_{3}-\bar{x}_{3} \\
          ..                \\
          x_{n}-\bar{x}_{n} 
 \end{array}
 \right)
   \left(
  \begin{array}{ccccc}
          x_{1}-\bar{x}_{1} &
          x_{2}-\bar{x}_{2} &
          x_{3}-\bar{x}_{3} &
          ..                &
          x_{n}-\bar{x}_{n} 
  \end{array}
  \right)
\end{equation}

对角线上是对应元素的方差,其他是相对于两个元素的协方差

Maximun likelihood

according to the given example finding the most likely distribution model
1, assign each instance a probability to be happen
2, descripte the the probability of all such instance happens
3, logarithm the probability
4, partial derivative the logarithm
5, set the partial derivative to be 0, get the probability in 1 step

linear Argebra

Matrix

Graph

digraph diagramm {
TransposeMatrix -> orthogonalMatrix[label = "A^TA = AA^T = 1"];
TransposeMatrix -> SymmetryMatrix[label= "A=A^{T}"];
SymmetryMatrix  -> HermitianMatrix[label= "A=A^{H}"];
HermitianMatrix -> positivedefinitematrix;
ConjugatetransposeMatrix -> NormalMatrix[label = "A*A = AA*"];
NormalMatrix  -> UnitaryMatrix[label = "A*A = AA* =1"] ;

Einzelwertzerlegung -> Diagroal [label = "SVD"] ;
Eigenwertzerlegung -> Diagroal [label = "for real and symmetrisch"];
Diagroal ->  Unitaryzerlegung [label ="A=VIV*,I:identity"];

}

transpose Matrix

symmetry conjugate

symmetry and complex conjugate matr

Symmetry Matrix

orthogonal matrix

实数酉矩阵 得该矩阵的转置矩阵为其逆矩阵

Hermitian matrix

A = symmetry conjugate of A (共轭对称) ,

埃尔米特矩阵,厄米特矩阵,厄米矩阵,所有元素对称出共轭

Conjugate transpose Matrix

共轭转置矩阵, 先共轭再转置,还是先转置再共轭都可以。

Normal Matrix

正定矩阵, 是转置和本身满足交换律 可酉变换

Unitary Matrix

酉矩阵,是正定矩阵, 即转置和本身满足交换律,而且等于 I

Eigenwertzerlegung

对于矩阵求特征值特征向量,特征值分解,但是要求必须是方阵,如果不是,先 要转换: A = a*a.T

import numpy as np
a = np.mat([[1,2,3,4],[1,1,1,1]])
A = a*a.T
B, U = np.linalg.eig(A)
print("eigenvalue of A : ")
print(B)
print("eigenvalue of a :(should be equal to the following) ")
print(np.sqrt(B))
print("eigenvactor : ")
print(U)

Einzelwertzerlegung

但是对于一般矩阵,不是方阵,可以奇异值分解:

import numpy as np
a = np.mat([[1,2,3,4],[1,1,1,1]])
U, B, Vt = np.linalg.svd(a)
print("left eigenvalue : ")
print(U)
print("eigenvactor of a : ")
print(B)
print("right eigenvalue : ")
print(Vt)

Transform

Jacobin matrix

wikipedia chinese link englich link

for , 由球坐标系到直角坐标系的转化由 F: ℝ+ × [0, π] × [0, 2π) → ℝ3 函数给出, 其分量为: 此坐标变换的雅可比矩阵是 其雅可比行列式为 r2 sin θ,由于 dV = dx dy dz,如果做变数变换的话其体 积元(Volume element),dV,会变成:dV = r2 sin θ dr dθ dφ。

Advanced Math Method

Fourier Problem

Fourier Series

任意周期函数都可以写成若干正余弦函数在不同频率的叠加, 假设目标函数为 so

or

And There is series orthometric basis (1, , ).

f(x) can also be wrote with complex form, , where

Fourier Transfromation

set , we use to multipy all terms in , which invokes factor .

SO and its inverse transfromation:

Laplace Transfromation

If ,we can use to eliminate divergence.

Laplace transfromation :

or , where

note: firstly force to convergence, then fourier transfromed.

Z-transform

where is the extractly continue signal function, presents that we only measured at time Kt, shows us all the measurements at time of...-2T, -T, 0, T, 2T, 3T...

The Fourier Transform of the measurements are ,

for , , this is Z Transform aber , , this is Distinct Fourier Transform

Distinct Fourier Transform

for , where , we only consider that, f(x) only has N items, from k=0, to N-1, and we has exactly N measurements points, , and we image that those N points is exactly in a period,which is from 0 to , so... set Here it is

\begin{equation}
  \left(  \begin{array}{c}
          f_{0} \\
          f_{1} \\
         f_{2} \\
        ....\\
        f_{N} 
 \end{array} \right)
=
  \left(
  \begin{array}{ccccc}
          1 &  1 & 1 & ...& 1\\
          1 &  w & w^{2} & ...& w^{N-1}\\
          1 &  w^{2} & w^{4} & ...& w^{2(N-1)}\\
          ...&...&...&...&...\\
          1 &  w^{N-1} & w^{2(N-1)} & ...& w^{(N-1)(N-1)}\\
  \end{array}
  \right)
  \left(
  \begin{array}{c}
          C_{0} \\
          C_{1} \\
         C_{2} \\
        ....\\
        C_{N} 
 \end{array}
 \right)
\end{equation}

We can have exactly all coefficient of C.

if we have only N measurements, but we want to have a general solution for all possible items of f(t), for ,

\begin{equation}
  \left(  \begin{array}{c}
          f_{0} \\
          f_{1} \\
         f_{2} \\
        ....\\
        f_{N} 
 \end{array} \right)
=
  \left[
  \begin{array}{ccccc}
          1 &  1 & 1 & ...& 1\\
          1 &  w & w^{2} & ...& w^{N-1}\\
          1 &  w^{2} & w^{4} & ...& w^{2(N-1)}\\
          ...&...&...&...&...\\
          1 &  w^{N-1} & w^{2(N-1)} & ...& w^{(N-1)(N-1)}\\
  \end{array}
  \right]
  \left(
  \begin{array}{c}
        ...+C_{-N} + C_{0}+C_{N}+... \\
         ...+C_{-N+1}+ C_{1}+C_{N+1}+... \\
         ...+C_{-N+2}+  C_{2}+C_{N+2}+... \\
        ...\\
         ...+C_{-1}+ C_{N-1}+C_{2N-1} +...
 \end{array}
 \right)
\end{equation}

All possible solutions can be satisfied. denote matrix as Fourier Matrix: F, ,

Fast Fourier Transform

we here only consider about , so denote it as ,

\begin{equation}
F_{4} =
\left[
  \begin{array}{cccc}
          1 &  1 & 1 & 1\\
          1 &  w & w^{2} & w^{3}\\
          1 &  w^{2} & w^{4}& w^{6)}\\
          1 &  w^{3} & w^{6}& w^{9}\\
  \end{array}
  \right]
  \end{equation}
\begin{equation}
\bar{F}_{4} =
\left[
  \begin{array}{cccc}
          1 &  1 & 1 & 1\\
          1 &  w^{2} & w & w^{3}\\
          1 &  w^{4} & w^{2}& w^{6)}\\
          1 &  w^{6} & w^{3}& w^{9}\\
  \end{array}
  \right]
=
\left[
  \begin{array}{cc}
         F_{2} & D_{2}F_{2}\\
         F_{2} & -D_{2}F_{2}
  \end{array}
  \right]
  \end{equation}

always recursive to , that is

Convolution law

Green function propagate function segment

convolution

Kalman Filter

descripation

For a continus system we can estimate the next predict state based on current optimized (best, precise) state and its uncertainies. if there is next observe state, we can combine them to a next optimized state and get its uncertainies, and ready for next iterative.

Estimatation Function:

stands for the state, with stands for the state Operator with stands for contoller operator is the current system uncertainies and with

Revise Function:

stands for the observe state, with stands for Observe Operator with is the observation uncertainies and with H = , , , ,

kalman filter process

assumpation: we know current state , and its uncertainies

  1. estimatation

all with

2, kalman filter calcaletation with : because Numerator has and denominator has

3, Revise resulte

python code

# _*_ coding:utf-8 _*_
import numpy as np
import matplotlib.pyplot as plt

# 创建一个0-99的一维矩阵
z = [i for i in range(100)]
z_watch = np.mat(z)
#print(np.array(z).shape)
#print(np.array(z_watch).shape)

# 创建一个方差为1的高斯噪声,精确到小数点后两位
noise = np.round(np.random.normal(0, 1, 100), 2)
noise_mat = np.mat(noise)
# print(noise_mat)

# 将z的观测值和噪声相加
z_mat = z_watch + noise_mat
#print(z_mat)

# 定义x的初始状态
x_mat = np.mat([[0, ], [0, ]])
# print(x_mat)
# 定义初始状态协方差矩阵
p_mat = np.mat([[1, 0], [0, 1]])
# 定义状态转移矩阵,因为每秒钟采一次样,所以delta_t = 1
f_mat = np.mat([[1, 1], [0, 1]])
# 定义状态转移协方差矩阵,这里我们把协方差设置的很小,因为觉得状态转移矩阵准确度高
q_mat = np.mat([[0.0001, 0], [0, 0.0001]])
# 定义观测矩阵
h_mat = np.mat([1, 0])
# 定义观测噪声协方差
r_mat = np.mat([1])

for i in range(100):
    x_predict = f_mat * x_mat
    p_predict = f_mat * p_mat * f_mat.T + q_mat
    kalman = p_predict * h_mat.T / (h_mat * p_predict * h_mat.T + r_mat)
    x_mat = x_predict + kalman * (z_mat[0, i] - h_mat * x_predict)
    p_mat = (np.eye(2) - kalman * h_mat) * p_predict
    plt.plot(x_mat[0, 0], x_mat[1, 0], 'ro', markersize=1)
plt.show()

Grope Theorie

sammlungen von Grope

  1. G本身和单位元称为G的平凡子集
  2. 群的元素个数称为群的阶
  3. 群的阶数是素数,则该群一定是循环群
  4. 有限群的子集的阶数是该有限群的阶数的约数
  5. 在置换群中,任何一个轮换都可以用其他的对换组合来实现
  6. 在置换群中,如果一个置换能通过奇(偶)数次对换得到,那么它只能有奇 (偶)数次对换得到
  7. 在一个置换群中,可以奇置换和偶置换的个数应给相等
  8. 由偶置换可以得到一个交错群(包括与单元群的置换)
  9. 阿贝尔群
  10. 元素 左乘H的每一个元素得到的就叫: 元素 关于H的左陪集
  11. 右陪集亦然, 左右陪集可以不相等
  12. 子群H中每个元素作用于群G,得到的左右陪集都相等,则称H为G的正规子群
  13. G本身和单位元{e}肯定都是正规子集,但是成为平凡正规子群
  14. 只有群中有正规子集,这该群中肯定存在一个相应的对称
  15. 阿贝尔群的子群肯定是正规子群
  16. 只有当H是正规子群是,商群G/H才是一个群,否则只是一个空间
  17. 单群,没有正规子群的群,是群论中的最小单元

title: Physik

#+startup: content

Classical physics

Particle physics

GR

Quantum


title: Qutuam Computation

#+STARTUP: overview

Basic states and operations

ketbra

  • Ket:

  • Bra:

  • Production of Ket and Bra:

states

If a measurement will collapse either on |0⟩ or |1⟩, which means |0⟩ or |1⟩ is its eigentstate, we call it as Z-measurement, and denote as .

If a measurement will collapse either on |+⟩ or |-⟩, which means |+⟩ or |-⟩ is its eigentstate, we call it as X-measurement, and denote as .

If a measurement will collapse either on |+i⟩ or |-i⟩, which means |+i⟩ or |-i⟩ is its eigentstate, we call it as Y-measurement, and denote as .

The coefficient has to be because of normalisation.

Measurements

for states basis of{ } and { }, the measurement of state on { } is .

Single Qutantum circuits

  • bit flip: :

  • phase flip: :

  • bit & phase filp: :

  • Hadamard gate: , ,

  • Phase gate: ,

Multipartite quantum states

we use tensor products to describe multiple states only such can to described by of other states are called uncorrelated, otherweise it's correlated, and when some fully correlated are called entangled.

XOR gate

#+header: :headers '("\\usepackage{qcircuit}")
\Qcircuit @C=1em @R=1em {
\lstick{\ket{x}} & \ctrl{1} & \rstick{\ket{x}} \qw \\
\lstick{\ket{y}} & \targ   & \rstick{\ket{x \oplus y }} \qw
}

Photo Link here

Bell states

Example of fully correlated states (maximally entangled),

Create Bell states

#+header: :headers '("\\usepackage{qcircuit}")
\Qcircuit @C=1em @R=1em {
\lstick{\ket{i}_A} & \gate{H} & \ctrl{1} &  \qw \\
\lstick{\ket{j}_B} &  \qw    &   \targ   &  \qw
  }

Photo Link here

Teleportion

If Alise and Bob share the same bell states , Now Alias want to send stetas to Bob,

  • Alice preforms a measurement in the Bell basis
  • she send her classical output (i,j) to Bob
  • Bob apply to get the orignal .
#+header: :headers '("\\usepackage{qcircuit}")
\Qcircuit @C=1em @R=.7em {
 \lstick{\ket{\phi_s}_A}          & \multigate{1}{Bell Meas} & \cw & \cw    & \cwx[2] \\
 \lstick{\ket{\varphi^{00}_A}}    & \ghost{Bell Meas}        & \cw & \cwx[1]   \\
 \lstick{\ket{\varphi^{00}_B}}    &  \qw                    & \qw & \gate{\sigma_x^j}& \gate{\sigma_x^j }& \qw &  \rstick{\ket{\phi_s}_B} 
}

Photo Link Here

Deutsche-Jose

Bit oracle

#+header: :headers '("\\usepackage{qcircuit}")

Photo Link here

, : phase oracle, which is independt of y, .

Hadamard on n qubits

for , ,

for for , , , ,

Deutsche Jose algorithm

#+header: :headers '("\\usepackage{qcircuit}")
\Qcircuit @C=1em @R=1em {
\lstick{\ket{0}}  & \gate{H} & \multigate{2}{U_f} & \gate{H} & \meter & \cw  & \rstick{\ket{y_0}} \\
\lstick{\ket{0}} & \gate{H} & \ghost{U_f} & \gate{H} & \meter & \cw  & \rstick{\ket{y_1}} \\
\lstick{\ket{0}} & \gate{H} & \ghost{U_f} & \gate{H} & \meter & \cw  & \rstick{\ket{y_n}} 
}

Photo Link here

Proof:

because , so ,

The Probability to measure the Zero( ) string is: if f is constant, and if f is balanced

Gover's Algrithmus


title: ROS

#+startup: content

Note

catkin~make~ 可以代替老式的rosbuild 最简单的package,只包括CMakelist.txt和package.xml 每一个roscore就已经打开了master 执行一个节点 rosrun 包名 节点名

通信方式

Topic

异步通信 多节点 Topic(rostopic) 多节点 msg对象 msg类型(rosmsg) msg对象

Service

同步通信 多节点 Service (rosservice) 单服务 srv对象 srv类型(rossrv) srv类可以嵌套msg类

Param

Parameter Service rosparam

Action

action


author: Silin title: Collected Tools

#+STARTUP: overview

金句

  • 光着屁股推磨, 转着圈的丢人
  • 不让我上桌,我就拉锅里
  • 撅着屁股上供,现了大眼了

software

kdenlive

clip

剪切片段后删除 提取部分片段 画音分离 擦除融入 整体后移 多选后一起移动 锁定

Titel

字体 背景 融入

effect

faden in faden out change speed transfrom(放缩) crop

sounds

Fadin Fadout Gain Mute Volume(keyframe)


title: Webdesige

#+startup: overviews

Factory mode

one product one factory many many design

一个产品,在一个工厂里有多个设计实现

one product many factory many design

一个产品,在多个各自的工厂里,有自己特有的设计实现

many product many factory many design

对于多个产品,在多个各自的工厂里,有自己特有的对每个产品的设计实现

project build digraph

digraph diagramm {
        Emacs  [shape=box,color=red]
        LspJavaSpringInitizer [shape=box,color=red]
        Config [shape=box,color=red]
        dapDebug [shape=box,color=red]
        Programmierung [shape=box,color=red]
        Terminal ->  Maven建包;
        Maven建包 -> Maven加依赖pom;
        Maven加依赖pom -> OpenEmacsFile;
        OpenEmacsFile ->   Programmierung;
        Programmierung -> MavenCompile;
        MavenCompile -> MavenPackage;
        MavenCompile -> dapDebug[label = "也可./mvnx"];
        MavenPackage -> 执行jar包;
        MavenPackage -> dapDebug;
        执行jar包 -> dapDebug;
        Emacs -> LspJavaSpringInitizer;
        LspJavaSpringInitizer -> Config;
        Config -> Programmierung;
        Programmierung -> dapDebug;
        dapDebug -> Webbroser;
}

1 add the to the above SRC begin:  dot :file ../sysconf/foto/webbuild.png
2 delete the output :  [[file:../sysconf/foto/webbuild.png]]
3 push the sysc repository, because the foto is located in it
4 add the link from sysc repository  https://github.com/scofild429/sysc/blob/master/foto/webbuild.png

WordPress Web development in AWS

构建后台

没事不要执行该代码

cd ~/Documents/web/key_aws
ssh ubuntu@3.124.205.43 -i pass1aws.pem
sudo apt update -y
sudo apt upgrade -y
sudo apt install apache2
sudo systemctl status apache2
sudo systemctl enable apache2
sudo apt install mariadb-server mariadb-client
sudo systemctl start mariadb
sudo systemctl status mariadb
sudo mysql_secure_installation ...
sudo systemctl restart mariadb
sudo apt install php php-mysql php-gd php-cli php-common
sudo apt install wget unzip
sudo wget https://wordpress.org/latest.zip
sudo unzip latest.zip
sudo cp -r wordpress/* /var/www/html/
cd /var/www/html/
sudo chown www-data:www-data -R /var/www/html/
sudo rm index.html 
## Now go to the IP webseit, when need database, do so
sudo mysql -u root -p
Enter
##  create database wordpress;
create database wordpress;
create user "wpadmin"@"%" identified by "wpadminpw";
grant all privileges on wordpress.* to "wpadmin"@"%";
exit;

back to the IP webseit, pass the database , username and password, set username and password for wordpress, 到此,可以用IP 地址访问前端和后台了

解析域名

route53, 用域名创建NS A-IPV4,名称为空, 值为IP CNAME,名称www, 值为域名 再将A 和CNAME 放到namecheap的域名的DNS管理中

ssl

sudo a2enmod ssl
sudo systemctl restart apache2
cd ~
wget https://dl.eff.org/certbot-auto
chmod a+x certbot-auto
sudo ./certbot-auto --apache....

go to https://www.sslshopper.com/ssl-checker.html and check you domina

scp

transfer file to linux instance of CE2

scp -i pass1aws.pem init.el ubuntu@3.124.205.43:.emacs.d

external html

  • 将文件传到部署根目录
  • 复制文件xxx.html 为page-xxx.php到应用主题根目录
  • 创建页面,先只写标题,保存后改别名,slug 为xxx
  • 发布后,将页面设为菜单就能访问

Web Design Envirement in Emacs

lsp-mode

lsp-java

dap-mode

Spring Boot

Emacs : M-x lsp-java-springboot-generate after build the project, it can be compiled by Maven,and run

project build digraph

digraph diagramm {
        Emacs  [shape=box,color=red]
        LspJavaSpringInitizer [shape=box,color=red]
        Config [shape=box,color=red]
        dapDebug [shape=box,color=red]
        Programmierung [shape=box,color=red]
        Terminal ->  Maven建包;
        Maven建包 -> Maven加依赖pom;
        Maven加依赖pom -> OpenEmacsFile;
        OpenEmacsFile ->   Programmierung;
        Programmierung -> MavenCompile;
        MavenCompile -> MavenPackage;
        MavenCompile -> dapDebug[label = "也可./mvnx"];
        MavenPackage -> 执行jar包;
        MavenPackage -> dapDebug;
        执行jar包 -> dapDebug;
        Emacs -> LspJavaSpringInitizer;
        LspJavaSpringInitizer -> Config;
        Config -> Programmierung;
        Programmierung -> dapDebug;
        dapDebug -> Webbroser;
}

1 add the to the above SRC begin:  dot :file ../sysconf/foto/webbuild.png
2 delete the output :  [[file:../sysconf/foto/webbuild.png]]
3 push the sysc repository, because the foto is located in it
4 add the link from sysc repository  https://github.com/scofild429/sysc/blob/master/foto/webbuild.png

webbuild.png

appeared Problem

server is not startup

1, workspace 有重叠和包含, 2, 需要重启 lsp mode

can't find the main class to start project

mvn compile 出现问题,大多数时候是依赖的问题

没有对应的补全

mvn 依赖的version 不同会有不同的包,补全也不同

MySQL

事务隔离

1 可同时访问修改 脏读 2 隔离访问 不可重返读 3 单人访问 幻读

single java file connect to mysql

1.download the driver to a current to java file

official web, and in my case

mysql-connector-java-8.0.20.jar

2.add the current path to the CLASSPATH

export CLASSPATH=mysql-connector-java-8.0.20.jar:.

3.compile and connect

execute as a jar file

if I want to package them to a package to a jar starkoverflow hitting and this plugin to pom.xml

<build>
  <plugins>
    <plugin>
      <artifactId>maven-assembly-plugin</artifactId>
      <configuration>
        <archive>
          <manifest>
            <mainClass>fully.qualified.MainClass</mainClass>
          </manifest>
        </archive>
        <descriptorRefs>
          <descriptorRef>jar-with-dependencies</descriptorRef>
        </descriptorRefs>
      </configuration>
    </plugin>
  </plugins>
</build>

and run with : mvn clean compile assembly:single

and then mvn package

can be called by jar file

java -cp target/xxxx....xx.jar com.mycompany.app.App

springboot

just call the plugins at the start

事务 Transaction

声明式:Annoation
1, 配置事务管理器
2, 开启事务注解
3, 添加事务注解
@Transaction(propagation, isolation, timeout, readout, (no)rollback)
propagation;事务是否传播
isolation:
脏读:未提交的事务读取到另一个未提交的事务的原始数据
不可重复读;未提交的事务读取到另一个提交的事务的原始数据
幻读;未提交的事务读取到另一个提交的事务的修改数据

范式


原子性 一致性 隔离性 持久性


连接池

外键

多表

execute in emacs

  1. create mvn project
  2. find the plugin of mysql and add it to pom.xml
  3. programmierung
  4. the connection can be call in the dabug of emacs

M-x :dap-debug

MongoDB

install

go to official seit and stetp by step

commonds functions


or $inc in $mul exist $rename gl $set sort $unset limit
skip
upsert
rename
getIndexs
createIndex
dropIndex

sudo systemctl start mongod
#+RESULTS:

create database, collections, and drops

:admin at the first step, we must login into one database

show dbs;
use xiaoma;
db.createCollection("posts");
show collections;
db.posts.drop();
db.dropDatabase();

create database, collections, and documents


use xiaoma;
db.createCollection("posts");
show collections;

db.posts.insert({ 
    title: "my first blog",
    content: "can be start"
});
db.posts.insert({ 
    title: "my second blog",
    content: "can be start now",
    tag: ["unknow type"]
});

for(var i = 3;i<=10;i++){
    db.posts.insert( {title :"this is my "+i+"th blog"});
};
db.posts.find();
db.posts.count();
db.posts.remove({});
db.posts.drop();
db.dropDatabase();

backup and restore

mongo xiaoma : can just get in xiaoma database

01, create documents

use xiaoma;
db.createCollection("posts");
show collections;

db.posts.insert({ 
    title: "my first blog",
    content: "can be start"
});
db.posts.insert({ 
    title: "my second blog",
    content: "can be start now",
    tag: ["unknow type"]
});

for(var i = 3;i<=10;i++){
    db.posts.insert( {title :"this is my "+i+"th blog"});
};

db.posts.find();
db.posts.count();

02, dump

cd ~/Desktop/
mkdir mongobk
cd mongobk
mongodump -d xiaoma

03, delete documents

use xiaoma;
db.posts.remove({});
db.posts.find();
exit;

04, restore

cd ~/Desktop/mongobk
mongorestore --drop

05, check

use xiaoma;
db.posts.find();
db.posts.drop();
db.dropDatabase();

fastdfs

libfastcommon & fastdfs

install

sudo ./make.sh install 查看tracker和storage的执行脚本,安装后必须存在 ll etc/init.d | grep fdfs

create location of tracker and stoarge

mkdir ~/Dokumente/WebDev/fastdfs/client mkdir ~/Dokumente/WebDev/fastdfs/tracker mkdir ~/Dokumente/WebDev/fastdfs/storage

copy config

sudo cp /etc/fdfs/client.conf.sample /etc/fdfs/client.conf sudo cp /etc/fdfs/tracker.conf.sample /etc/fdfs/tracker.conf sudo cp /etc/fdfs/storage.conf.sample etc/fdfs/storage.conf sudo cp //etc/fdfs/storage~ids~.conf.sample //etc/fdfs/storage~ids~.conf

config tracker stoarge client

cd /etc/fdfs copy all config file as modification file

tracker: 修改base~path~ 为新建的tracker目录full name

storage: base~path~ 为新建的storage目录full name store~path~ 为新建的storage目录fullname tracker-server:内网加tracker的端口

client: base~path~: 为新建的client目录full tracker-server:内网加tracker的端口

open port

open port sudo firewall-cmd --add-port=80/tcp --permanent sudo firewall-cmd --add-port=23000/tcp --permanent sudo firewall-cmd --add-port=22122/tcp --permanent restart firewall: sudo firewall-cmd --reload

start and test

sudo /usr/bin/fdfs~trackerd~ /etc/fdfs/tracker.conf start sudo /usr/bin/fdfs~storaged~ /etc/fdfs/storage.conf start sudo /usr/bin/fdfs~test~ /etc/fdfs/client.conf upload /etc/fdfs/110.png

Or

this can be don't work for Unit fdfs~storaged~.service not found sudo service fdfs~trackerd~ start sudo service fdfs~trackerd~ start

/usr/bin/fdfs~uploadfile~ /etc/fdfs/client.conf ~/Bilder/110.png

fastdfs-nginx-mode

将config中的 ngx~moduleincs~="/usr/local/include" and CORE~INCS~= ="$CORE~INCS~ /usr/local/include" 改为: ngx~moduleincs~="/usr/include/fastdfs /usr/include/fastcommon" CORE~INCS~= ="$CORE~INCS~ /ur/include/fastdfs /usr/include/fastcommon"

再将config同目录下的mod~fastdfs~.conf 复制到/etc/fdfs/中 and modify:

  • tracker~server~ just like in storage.conf
  • url~havegroupname~ = true
  • store~path0~ just like in storge.conf

最后将fastdfs中conf中的http.conf和mime.types复制的/etc/fdfs/

nginx with fdfs

apt-get install libpcre3 libpcre3-dev apt-get install libpcre3 zlib1g apt-get install libpcre3 zlib1g-dev ./configure --prefix=/opt/nginx --sbin-path=/usr/bin/nginx --add-module=../fastdfs-nginx-module-1.20/src make sudo make install

location ~/group([0-9]){ ngx~fastdfsmodule~; }

cd usr/bin ./nginx

OR: sudo /usr/bin/nginx -s reload

IDEA config

#fastdfs设置
fdfs:
  so-timeout: 2500       # 读取时间
  connect-timeout: 5000   # 连接超时时间
  thumb-image:           # 缩略图
    width: 100
    height: 100
  tracker-list:          # tracker服务配置地址列表
    - localhost:22122
upload:
  base-url: localhost/
  allow-types:
    - image/jpeg
    - image/png
    - image/bmp

Nodejs newest install

current releast

sudo apt-get install curl 
curl -sL https://deb.nodesource.com/setup_16.x | sudo -E bash -

LTS release

sudo apt-get install curl 
curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash - 

install and upgrade

sudo apt-get install nodejs
sudo npm install -g install

Yarn newest install

yarn can be installed by npm, and yarn --version works, but only for old old version

for yarn init comes the error: "00h00m00s 0/0: : ERROR: [Errno 2] No such file or directory: 'init'"

delete yarn and reinstall it

sudo apt remove cmdtest
sudo apt remove yarn
curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -
echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list
sudo apt update
sudo apt upgrade

for upgrade comes the error:

ModuleNotFoundError: No module named 'uaclient'
dpkg: Fehler beim Bearbeiten des Paketes ubuntu-advantage-tools (--configure):
 »installiertes ubuntu-advantage-tools-Skript des Paketes post-installation«-Unterprozess gab den Fehlerwert 1 zurück
Fehler traten auf beim Bearbeiten von:
 ubuntu-advantage-tools
E: Sub-process /usr/bin/dpkg returned an error code (1)

Normally in one package is not complete in dpkg or apt,

sudo dpkg --configure -a

or

sudo apt install -f
sudo apt install--fix-broken

works, but if not, remove it if possible so ubuntu-advantage-tools should be removed,

sudo apt-get remove ubuntu-advantage-tools
sudo mv /var/lib/dpkg/info/ubuntu-advantage-tools.* /tmp/
sudo dpkg --force-remove-reinstreq --purge ubuntu-advantage-tools
sudo dpkg --remove --force-remove-reinstreq ubuntu-advantage-tools

then

sudo apt update
sudo apt upgrade
sudo apt install yarn
yarn --version

new version can be shown, and yarn init works

JS

some ES6 has to be connected JS to here,

ts

after change the tsconfig.json, use the command to compile ts to js continual.

tsc -watch

npm

npm build
sudo npm i -g serve
serve -s dist
sudo npm i json-server

list all installed packages npm list -g --depth=0 npm uninstall reveal.js

nvm

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
nvm ls-remote
nvm install node (the least version)
nvm ls
nvm install v16.13.1
nvm ls
nvm install v17.2.0
nvm ls

Webpack

npm init -y
npm i -D webpack webpack-cli typescript ts-loader

设定生成的html的特性,包括使用模板
npm i -D html-webpack-plugin

设定项目的运行服务器
npm i -D webpack-dev-server
in package.json/"scripts":      "start": "webpack serve --open chromium-browser"
and then in terminal: npm start


删除上次的生成文件,整个dist目录
npm i -D clean-webpack-plugin
const path = require("path");

const HTMLWebpackPlugin = require("html-webpack-plugin");

const { CleanWebpackPlugin } = require("clean-webpack-plugin");

module.exports = {
    entry: "./src/index.ts",
    output: {
        path: path.resolve(__dirname, "dist"),
        filename: "bundle.js",
        // environment: {
        //     arrowFunction: false,
        // },
    },
    module: {
        rules: [
            {
                test: /\.ts$/,
                use: [
                    {
                        loader: "babel-loader",
                        options: {
                            presets: [
                                [
                                    "@babel/preset-env",
                                    {
                                        targets: {
                                            chrome: "87",
                                            // ie: "11",
                                        },
                                        corejs: "3",
                                        useBuiltIns: "usage",
                                    },
                                ],
                            ],
                        },
                    },
                    "ts-loader",
                ],
                exclude: /node-modules/,
            },
        ],
    },
    plugins: [
        new HTMLWebpackPlugin({
            title: "APP For Webpack",
        }),
        new CleanWebpackPlugin(),
    ],

    //模块设定
    resolve: {
        extensions: [".ts", ".js"],
    },
};

webpack: Permission denied

sudo chmod 777 ./node_modules/.bin/webpack

JQuary

select element

JQuery选择器


elements chooser class chooser id chooser name $("p"), $("div"), $("h2") $(".test") $("#test") $("[name=name]")


CSS 选择器


elements chooser class chooser id chooser p, div, h2 .test #test


JQuery思想 方法函数化 方法链式化, 取值赋值一体化

$(function(){
    $("h1").click(function(){
        alert("nihao");
    });
    $("h1").mouseout(function(){
        this.style.backgroundColor = "red";
    });
    $("h1").mouseover(function(){
        this.style.backgroundColor = "blue";
    });
});

$(function(){
    $("h1").click(function(){
        alert("nihao");
    }).mouseout(function(){
        this.style.backgroundColor = "red";
    }).mouseover(function(){
        this.style.backgroundColor = "blue";
    });
});

$("div").html()
$("input").val()

function

filter

not

has

prev

next

find

eq

index

attr

addClass

removeClass

on

off

width

width innerWidth outerWidth

scrollTop

operation function


toggle fade slide animate stop clain text html val attr append prepend after before remove empty addclass removeclass css width height perent childen siblings load get post noConflict


AJAX

Servlet

Bootstrap

Spring

sammelung:


Component inject the class into Spring from current file as bean ComponentScan load the bean into current file from Spring as class Autowired complete all beans dependence with the beans in spring Configuration configuration class


模式: 单例和多例:生命周期:创建和销毁时间

Annotation mehthod

@Component

将所修饰的类做成bean,由 Spring 来管理 为了减少耦合,建立一个配置类来管理全部的bean 由 @Configuation and @ComponentScan 创建的配置类来管理。 注意Spring只是默认管理@ComponentScan所在的其以下的区域, 除非指定包名,可以到其上一级的包路径

web hierarchy with @component

Controller layer use @Controller than @Component Service layer use @Service than @Component Dao layer use @Repository than @Component

autowired

  • Set注入 利用set方法
  • cost注入 利用构造方法,可和set 注入混用
  • 普通成员变量
  • 普通成员函数

interface with @Autowired


注入 @Compenten 加在实现类 装配 @Autowired 放在该接口的类型前 产生歧义 多个Autowired 如果该接口有多个实现类,不知道用那个实现类的bean 首选bean @Primary 多个实现类的Compenten注入时,可制定唯一一个实现类为首 限定附 @Qualifier("xxx") 在Autowired时,使用一样的 @Qualifier("xxx") bean id @Compenten("xxx") 同样在Autowired时,使用一样的 @Qualifier("xxx") 默认bean id xxx即为类名 在Autowired时 @Qualifier("xxx")时,类名首字母小写即可 二合一 @Resource(name="小写类名") 代替Autowired 和Qulifier()


xml mehthod

New-> XML Configuration File -> Spring Config default name: ApplicationContext.xml

<bean class="xxx.xxx.xxx.class" id="" (gleich wie name="") 别名可以多个,隔开即可 <consturctor-arg ref="beanid"> für contributor bean <consturctor-arg name="xxx" value="yyy"> für contributor string c:contributor C名称空间 <list> <map> <set> <p> <util> <properties> ... ><bean>

bean method

Don't use @Component or Service Controller Repository to inject bean(IOC) with a config class @Configuation Use @bean on it's consturctor function to inject bean. 对其多实现类的歧义性处理,和自动装配一样,@Primary @Qualifer and BEANID

seter

passing the contributor bean can use setter function

consturctor

if a bean need another bean as contributor, the contributor can be passed as argument into consturctor function, or generated

advancd mehthod

function field


singleton default only one bean prototype scope="prototype" Session each inject request


lazy load bean

in xml: lazy-init="true" in Annotation: @Lazy with prototype, singleton is default as lazy

init and destroy

log4j

after injuct in pox.xml, create log4j.properties in project resources fold

log4j.rootCategory=INFO, stdout

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %t %c{2}:%L - %m%n

log4j.category.org.springframework.beans.factory=DEBUG

Test


@RunWith @ContextConfiguration

AOP

动态代理,(JDK,接口) (CGLib, 接口)

前置,后置,环绕 class 1 -> Bean 1 Bean 1 + pointcut(expression,within,args) + class 2 -> Bean 2

Concept

连接点:可增强的方法 切入点: 实际上被增强的方法 通知(增强):增强的内容

  • 前置 Before
  • 后置 After 增强之后,return 之前,有异常也执行
  • 环绕 Around
  • 异常 AfterThrowing 有异常才执行
  • 最终 AterRreturning return 之后才执行,有异常不执行

切面:将增强内容应用到切入点

AspectJ

  • xml
  • Annotation

切入点表达式 @Pointcut @Oder()

JDBC

JDBC Template update(sql, args) 增删改 queryForObject()查 query() bachtupdate()

SpingMVC

Web action --> 前端控制 --> Path --> 后端 --> handler --> 前端 backend reserver arguments.

  1. single argument
  2. multi arguments
  3. class instance

C -> C redirect 重定向 刷新后会重复提交增删改 C -> V forward 转发 查询需要转发


-Dfile.encoding=utf-8 for Tomcat server VM Options: backend output for chineseisch

C-> V assugment request session model

Spring Boot

JDBC

  • Driver
  • connection
  • mysql
  • execute
  • statement
  • preperedstatement
  • close

mybatis

framework

springboot

  1. pom.xml

    <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.3.0</version> </dependency>

  2. application.yml

    配置mybatis, 指示Mapper.xml的位置 mapper-locations: classpath:mapper/*/*Mapper.xml

    1. Mybatias configuration(appeared.yml)


      prppreties settings typeAliases typeHanders plugins envirements mapper(url, resource, class, Annotation)

    2. *Mapper.xml


      query: resultMap/resultType insert, update, delete: parameterType


  3. Applicaton.java

    启动类, 指示bean扫描的位置 @MapperScan(basePackages = {"com.sxt.system.mapper"})

  4. Route

    web requirement -> controller -> server -> serverIpm -> *Mapper.xml(self def) 自定义的在*Mapper.xml内找到数据库的入口, 默认的可以直接调用。

spring

# and $

  1. # will add ' ' around the given paramenters, so it's saft, with concat
  2. $ will not add ' ', it's not safe

include

<sql id="commonField" id, goodname, price </sql>

Select <include refid="commonField" />

流程

  • 获取字节输入流
  • 构建SqlSessioFactory
  • 生产SqlSession
  • 执行Dao
  • 释放资源

延迟加载

缓存

一级缓存

SqlSession

二级缓存

SqlSessionFactory

注解开发

Shiro

c3p0

Rruid

nginx

https ssl deployment

1, just deploy my web seit normally, and can be access by http 2, sudo apt install certbot python-certbot-nginx 3, sudo certbot certonly --nginx (will be asked) 4, sudo certbot install --nginx

local Nginx deployment

install

yum install -y pcre pcre-devel
yum install -y zlib zlib-devel
yum install -y openssl openssl-devel


tar
mv xxx nginx
mv nginx /usr/local/src/
cd /usr/local/src/nginx
mkdir /usr/nginx
./configure --prefix=/usr/nginx
make
make install

sudo apt install nginx

etc/nginx 是其配置文件夹,里面有很多include文件, nginx 的默认设置在其中一个 default 文件里。 本机html仓库 /var/www/html 将项目放在此文件夹下,运行对于的端口即可 本机开机后,该文件的会被自动部署,端口可见

fire wall 80 port if necessary

add port :
sudo apt install firewalld
sudo firewall-cmd --add-port=80/tcp --permanent
sudo firewall-cmd --remove-port=80/tcp --permanent
restart firewall:
sudo  firewall-cmd --reload
check port:
sudo  firewall-cmd --list-all

nginx control

sudo apt systemctl stop nginx
nginx -s stop
sudo apt systemctl start nginx
nginx -s reload

uninstall

sudo apt-get purge nginx nginx-common

Nginx with php

sudo apt install nginx sudo systemctl restart nginx sudo apt install php sudo apt install php-fpm check if exit: /var/run/php/php7.2-fpm.sock

emacs /etc/php/7.2/fpm/pool.d/www.conf -> listen = /run/php/php7.2-fpm.sock

cd /etc/nginx/sites-available emacs default

list  post
root  folder
location ~ \.php{
     include snippets/fastcgi-php.conf;
     fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
     include fastcgi_params;
}

vollstandig

################### 9020 FOR php ##################################################################################
server {
    listen 9020;
    listen [::]:9020;

    # SSL configuration
    #
    # listen 443 ssl default_server;
    # listen [::]:443 ssl default_server;
    #
    # Note: You should disable gzip for SSL traffic.
    # See: https://bugs.debian.org/773332
    #
    # Read up on ssl_ciphers to ensure a secure configuration.
    # See: https://bugs.debian.org/765782
    #
    # Self signed certs generated by the ssl-cert package
    # Don't use them in a production server!
    #
    # include snippets/snakeoil.conf;

    root /home/sx/Documents/nginx9020;

    # Add index.php to the list if you are using PHP
    index index.html index.htm index.nginx-debian.html index.php;

    server_name _;

    location / {
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
        try_files uri uri/ =404;
    }

    # pass PHP scripts to FastCGI server
    #
    location ~ \.php {
        include snippets/fastcgi-php.conf;

        # With php-fpm (or other unix sockets):
        fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
        # With php-cgi (or other tcp sockets):
        include fastcgi_params;
        #fastcgi_pass 127.0.0.1:9000;
    }

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    #location ~ /\.ht {
    #   deny all;
    #}
}

apache2

sudo apt install apache2 sudo systemctl restart apache2 cd etc/apache2

  1. ports.conf -> add new post
  2. appache.conf -> add new folder
  3. cd sites-available emacs 000-default.conf -> add server of post and folder

Maven

package all the dependencies together as a jar

if I want to package them to a package to a jar starkoverflow hitting and this plugin to pom.xml

<build>
  <plugins>
    <plugin>
      <artifactId>maven-assembly-plugin</artifactId>
      <configuration>
        <archive>
          <manifest>
            <mainClass>fully.qualified.MainClass</mainClass>
          </manifest>
        </archive>
        <descriptorRefs>
          <descriptorRef>jar-with-dependencies</descriptorRef>
        </descriptorRefs>
      </configuration>
    </plugin>
  </plugins>
</build>

package and Execute

  • run with : mvn clean compile assembly:single
  • mvn package

and now this jar file can be called

  • java -cp target/xxxx....xx.jar com.mycompany.app.App

customize locally archetype

to the local repository

cd ~/.m2/repository/org/apache/maven/archetypes/maven-archetype-quickstart/1.4/

open the jar file, and change the pom.xml

Session und Cookie

  1. Browser send request to server with name, password...
  2. if the authentication is passed, server generate a SessionID,

and search the results, giving back browser response(name, password, results Sessionid..) Sessionid will be saved in SERVER.

  1. get the response, browser save the name, password and Sessionid as

Cookie.

  1. send request again, browser get the name, password, and Sessionid from Cookie, and send the requests
  2. server check the Sessionid only if possible, and send the results and name, password again as response back to browser.

Only the first time response, Sessionid will be send back to browser.

URL重写(常用),就是把session id直接附加在URL路径的后面

HTTP Proposal

http Request


Request Line request type + url path(many kinds of paramenters)+ http version Header: Host; Cookie; Content-type; User-Agent... Request Body: username="admin"&password="admin"


Http Response


esponse Line: http version + state code + state string Header: Content-type (describe information) Response Body: <html> ....</tml>


appeared Problem

server is not startup

1, workspace 有重叠和包含, 2, 需要重启 lsp mode

can't find the main class to start project

mvn compile 出现问题,大多数时候是依赖的问题

没有对应的补全

mvn 依赖的version 不同会有不同的包,补全也不同

local jdk configuration

mkdir /usr/local/java
tar -zxvf jdkxxxxx.tar.gz -C /usr/localjava
sudo emacs -nw -q /etc/profile
->
JAVA_HOME=/usr/local/java/jdkxxxxx
PATH=<span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord mathnormal" style="margin-right:0.09618em;">J</span><span class="mord mathnormal">A</span><span class="mord mathnormal" style="margin-right:0.22222em;">V</span><span class="mord"><span class="mord mathnormal">A</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3283em;"><span style="top:-2.55em;margin-left:0em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight" style="margin-right:0.08125em;">H</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mord mathnormal" style="margin-right:0.05764em;">OME</span><span class="mord">/</span><span class="mord mathnormal">bin</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">:</span></span></span></span>PATH
CLASSPATH=.:<span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord mathnormal" style="margin-right:0.09618em;">J</span><span class="mord mathnormal">A</span><span class="mord mathnormal" style="margin-right:0.22222em;">V</span><span class="mord"><span class="mord mathnormal">A</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3283em;"><span style="top:-2.55em;margin-left:0em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight" style="margin-right:0.08125em;">H</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mord mathnormal" style="margin-right:0.05764em;">OME</span><span class="mord">/</span><span class="mord mathnormal" style="margin-right:0.01968em;">l</span><span class="mord mathnormal">ib</span><span class="mord">/</span><span class="mord mathnormal">d</span><span class="mord mathnormal">t</span><span class="mord">.</span><span class="mord mathnormal">ja</span><span class="mord mathnormal" style="margin-right:0.02778em;">r</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">:</span></span></span></span>JAVA_HOME/lib/tools.jar
export JAVA_HOME
export PATH
export CLASSPATH

source /etc/profile

Django

TVM archetype

TVM design

uwsgi domain example

this has perhaps to be connected with ssl nginx $ uwsgi --chdir /home/cloud/django/QL --http :8000 --module QL.wsgi:application $ uwsgi --ini ql~uwsgi~.ini

Projekt StudyNet commands

pip install virtualenv virtualenv --python=python3.9 django source django/bin/active pip install django pip install django-restframework pip install django-cors-headers pip install djoser django-admin startproject studynet~django~

debug models small example

access to django shell

python manage.py shell
from Myapp.models import Publication, Article
p1 = Publication(title='The Python Journal') 
p1.save()
p1
p2 = Publication(title='Science News') 
p2.save()
p2
p3 = Publication(title='Science Weekly') 
p3.save()
p3
p4 = Publication(title='Science for everyone') 
p4.save()
a1 = Article(headline='Django lets you build Web apps easily')
a1.save()
a1.publications.add(p1)
a1.publications.add(p4)
a1.publications.all()
a2 = Article(headline='NASA uses Python')
a2.save()
a2.publications.add(p1, p2)
a2.publications.add(p3)
new_publication = a2.publications.create(title='Highlights for Children')
new_publication
p1.article_set.all()
a2.publications.all()
Publication.objects.get(id=4).article_set.all()
Article.objects.filter(publications__title__startswith="Science")
Article.objects.filter(publications__title__startswith="Science").distinct()

modelTOmodel

  • oneToone:
    • connected instance must saved at frist
    • in connecting instance creatation, the connected instance will be specified
    • connected.connecting
    • connecting.connected
  • ManyToone(ForeignKey)
    • connected instance must saved at frist
    • in connecting instance creatation, the connected instance will be specified
    • connecting.conneted
    • connected.connecting~set~.all()
  • ManToMany
    • connected instance must saved at frist
    • connecting instance must saved at frist
    • connecting.connected.add(connected)
    • connecting.conneted.all()
    • connected.connecting~set~.all()

Documents Collections

  • for choose filed, get the presented value with : instance.get~fieldnamedisplay~()

RuoYi-Vue project

backup deployment

redis

sudo apt install redis-server
sudo snap install redis-desktop-manager(not necessary)

sem /etc/redis/redis.conf
56 bind 127.0.0.1
507 requirepass 123456

sudo systemctl restart redis-server
or
sudo service redis-server restart

1. without password : redis-cli 
2. with password    : redis-cli -h localhost -p 6379 -a 123456
PING -> PONG

It may happen, even with requirepass, but still can login without pass.
The application based on this will be fail,
Need redis-cli login, and > auth "pass"
if returns OK, it works for Applications

mysql

tomcat

configuration for IDEA as local Tomcat

schnitt

redis mysql uploadPath system log.path check localhost:8080

ssh

set to be false

dependence from jdk8

<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.3.0</version>
</dependency>

<dependency>
    <groupId>com.sun.xml.bind</groupId>
    <artifactId>jaxb-impl</artifactId>
    <version>2.3.0</version>
</dependency>

<dependency>
    <groupId>com.sun.xml.bind</groupId>
    <artifactId>jaxb-core</artifactId>
    <version>2.3.0</version>
</dependency>

<dependency>
    <groupId>javax.activation</groupId>
    <artifactId>activation</artifactId>
    <version>1.1.1</version>
</dependency>

frontend deployment

build

cd ruoyi-ui
npm run build:prod
npm run build:stage
cp -r dist/* ~/Documens/nginx9010/

验证码 for nginx

#####################9010 NOT for php ############################################################################


server {
    listen 9010;
    listen [::]:9010;

    # SSL configuration
    #
    # listen 443 ssl default_server;
    # listen [::]:443 ssl default_server;
    #
    # Note: You should disable gzip for SSL traffic.
    # See: https://bugs.debian.org/773332
    #
    # Read up on ssl_ciphers to ensure a secure configuration.
    # See: https://bugs.debian.org/765782
    #
    # Self signed certs generated by the ssl-cert package
    # Don't use them in a production server!
    #
    # include snippets/snakeoil.conf;



    # Add index.php to the list if you are using PHP


    server_name _;

    location / {
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
        root /home/sx/Documents/nginx9010;
        index index.html index.htm index.nginx-debian.html index.php;
        try_files <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6595em;"></span><span class="mord mathnormal">u</span><span class="mord mathnormal" style="margin-right:0.02778em;">r</span><span class="mord mathnormal">i</span></span></span></span>uri/ =404;
    }

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    #location ~ /\.ht {
    #   deny all;
    #}

    location /prod-api/{
            proxy_set_header Host <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8889em;vertical-align:-0.1944em;"></span><span class="mord mathnormal">h</span><span class="mord mathnormal">tt</span><span class="mord"><span class="mord mathnormal">p</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3361em;"><span style="top:-2.55em;margin-left:0em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight">h</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mord mathnormal">os</span><span class="mord mathnormal">t</span><span class="mpunct">;</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord mathnormal">p</span><span class="mord mathnormal">ro</span><span class="mord mathnormal">x</span><span class="mord"><span class="mord mathnormal" style="margin-right:0.03588em;">y</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.1514em;"><span style="top:-2.55em;margin-left:-0.0359em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight">s</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mord mathnormal">e</span><span class="mord"><span class="mord mathnormal">t</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3361em;"><span style="top:-2.55em;margin-left:0em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight">h</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mord mathnormal">e</span><span class="mord mathnormal">a</span><span class="mord mathnormal">d</span><span class="mord mathnormal" style="margin-right:0.02778em;">er</span><span class="mord mathnormal" style="margin-right:0.07847em;">X</span><span class="mspace" style="margin-right:0.2222em;"></span><span class="mbin">−</span><span class="mspace" style="margin-right:0.2222em;"></span></span><span class="base"><span class="strut" style="height:0.7778em;vertical-align:-0.0833em;"></span><span class="mord mathnormal" style="margin-right:0.00773em;">R</span><span class="mord mathnormal">e</span><span class="mord mathnormal">a</span><span class="mord mathnormal" style="margin-right:0.01968em;">l</span><span class="mspace" style="margin-right:0.2222em;"></span><span class="mbin">−</span><span class="mspace" style="margin-right:0.2222em;"></span></span><span class="base"><span class="strut" style="height:0.6833em;"></span><span class="mord mathnormal" style="margin-right:0.07847em;">I</span><span class="mord mathnormal" style="margin-right:0.13889em;">P</span></span></span></span>remote_addr;
            proxy_set_header REMOTE-HOST <span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8889em;vertical-align:-0.1944em;"></span><span class="mord mathnormal">re</span><span class="mord mathnormal">m</span><span class="mord mathnormal">o</span><span class="mord mathnormal">t</span><span class="mord"><span class="mord mathnormal">e</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.1514em;"><span style="top:-2.55em;margin-left:0em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight">a</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mord mathnormal">dd</span><span class="mord mathnormal" style="margin-right:0.02778em;">r</span><span class="mpunct">;</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord mathnormal">p</span><span class="mord mathnormal">ro</span><span class="mord mathnormal">x</span><span class="mord"><span class="mord mathnormal" style="margin-right:0.03588em;">y</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.1514em;"><span style="top:-2.55em;margin-left:-0.0359em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight">s</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mord mathnormal">e</span><span class="mord"><span class="mord mathnormal">t</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3361em;"><span style="top:-2.55em;margin-left:0em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight">h</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mord mathnormal">e</span><span class="mord mathnormal">a</span><span class="mord mathnormal">d</span><span class="mord mathnormal" style="margin-right:0.02778em;">er</span><span class="mord mathnormal" style="margin-right:0.07847em;">X</span><span class="mspace" style="margin-right:0.2222em;"></span><span class="mbin">−</span><span class="mspace" style="margin-right:0.2222em;"></span></span><span class="base"><span class="strut" style="height:0.7778em;vertical-align:-0.0833em;"></span><span class="mord mathnormal" style="margin-right:0.13889em;">F</span><span class="mord mathnormal" style="margin-right:0.02778em;">or</span><span class="mord mathnormal" style="margin-right:0.02691em;">w</span><span class="mord mathnormal">a</span><span class="mord mathnormal" style="margin-right:0.02778em;">r</span><span class="mord mathnormal">d</span><span class="mord mathnormal">e</span><span class="mord mathnormal">d</span><span class="mspace" style="margin-right:0.2222em;"></span><span class="mbin">−</span><span class="mspace" style="margin-right:0.2222em;"></span></span><span class="base"><span class="strut" style="height:0.6833em;"></span><span class="mord mathnormal" style="margin-right:0.13889em;">F</span><span class="mord mathnormal" style="margin-right:0.02778em;">or</span></span></span></span>proxy_add_x_forwarded_for;
            proxy_pass http://localhost:8080/;
        }

        error_page   500 502 503 504  /50x.html;

    location = /50x.html {
            root   html;
        }

}

webpack

npm init -y
npm i -D webpack webpack-cli typescript ts-loader

设定生成的html的特性,包括使用模板
npm i -D html-webpack-plugin

设定项目的运行服务器
npm i -D webpack-dev-server
in package.json/"scripts":      "start": "webpack serve --open chromium-browser"
and then in terminal: npm start


删除上次的生成文件,整个dist目录
npm i -D clean-webpack-plugin
const path = require("path");

const HTMLWebpackPlugin = require("html-webpack-plugin");

const { CleanWebpackPlugin } = require("clean-webpack-plugin");

module.exports = {
    entry: "./src/index.ts",
    output: {
        path: path.resolve(__dirname, "dist"),
        filename: "bundle.js",
        // environment: {
        //     arrowFunction: false,
        // },
    },
    module: {
        rules: [
            {
                test: /\.ts$/,
                use: [
                    {
                        loader: "babel-loader",
                        options: {
                            presets: [
                                [
                                    "@babel/preset-env",
                                    {
                                        targets: {
                                            chrome: "87",
                                            // ie: "11",
                                        },
                                        corejs: "3",
                                        useBuiltIns: "usage",
                                    },
                                ],
                            ],
                        },
                    },
                    "ts-loader",
                ],
                exclude: /node-modules/,
            },
        ],
    },
    plugins: [
        new HTMLWebpackPlugin({
            title: "APP For Webpack",
        }),
        new CleanWebpackPlugin(),
    ],

    //模块设定
    resolve: {
        extensions: [".ts", ".js"],
    },
};

serve

sudo apt install serve
serve folder

Traefik

just load traefik

IN: docker-compose.yml

version: "3.8"
  services:
    traefik:
    image: traefik:alpine
    command: --api --docker
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
    ports:
      - 80:80
      - 8080:8080

open localhost:8080

load traefik with configaution

IN: traefik.toml

defaultEntryPoints = ["http"]

logLevel = "INFO"
sendAnonymousUsage = true

[docker]
  endpoint = "unix:///var/run/docker.sock"
  exposedByDefault = true

[api]
dashboard = true
entrypoint = "dashboard"

[entryPoints]
  [entryPints.http]
  address = ":80"

  [entryPints.dashboard]
  address = ":8080"

open localhost:8080

Oauth


Resource owner me Client myapp Authorization server google cloud project Resource server google account Authorization grant the whole process call back /redirect app api call Access token jwt token Scope ['client~id~'] Consent allow?


VScode

set the fontsize

settings: editor . fontsize:15 windows .zoomLevel: 1.5

Zen mode

hiden all stuff, only show code

Minmap

minmap of all code

switch in opened file

ctrl + tab

Emmet

"emmet.triggerExpansionOnTab": true

Quokka

M-x: new quokka js file will execute all in the new file

Better comments

open it in format on save

live server

M-x live server open file

Problem

maximun file number

System limit for number of file watchers reached, watch '/home/silin/Dokumente/WebDev/Vue/vueboot5/node_modules/webpack-dev-server/client/live.html'

Overstack description the Project need more file than the system can watch,

Ubuntu

sudo gedit /etc/sysctl.conf

Add a line at the bottom

fs.inotify.max_user_watches=524288

Then save and exit!

sudo sysctl -p

to check it

Then it is solved!

Mix of Tab and space

// .eslintrc.js module.exports = { "rules": { "no-mixed-spaces-and-tabs": 0, // disable rule } };

Unexpected tab character (no-tabs)

// .eslintrc.js module.exports = { "rules": { "no-tabs": 0 } };

Parsing error: Unexpected token <

// .eslintrc.js module.exports = { "root": true, "env": { "node": true }, "extends": [ "plugin:vue/essential", "eslint:recommended" ], "rules": { "no-mixed-spaces-and-tabs": 0, // disable rule }, "parserOptions": { "ecmaVersion": 6, "ecmaFeatures": { "experimentalObjectRestSpread": true }, "parser": "babel-eslint" } };

Expected indentation of 8 spaces but found 1 tab (indent)

rules: { 'indent': 'off' }

error:0308010C:digital envelope routines::unsupported

$: export NODE~OPTIONS~=--openssl-legacy-provider

scp to var/www/html permission dense

change the owner and group of html to be non root,

full stack deployment

  • frontend at 80
  • backend at 8000
  • nginx for reverse proxy under the server~name~ location api { proxy~pass~ http://localhost:8000; }

title: Vue

#+startup: overview

数据绑定

  1. 计算属性 在computed属性对象中定义计算属性的方法 在页面中使用{{方法名}}来显示计算的结果

  2. 监视属性: 通过通过vm对象的$watch()或watch配置来监视指定的属性 当属性变化时, 回调函数自动调用, 在函数内部进行计算

  3. 计算属性高级: 通过getter/setter实现对属性数据的显示和监视 计算属性存在缓存, 多次读取只执行一次getter计算

    
    const app = Vue.createApp({
        data() {
            return { count: 4 }
        }
    })
    
    const vm = app.mount('#app')
    
    console.log(vm.$data.count) // => 4
    console.log(vm.count)       // => 4
    
    // 修改 vm.count 的值也会更新 $data.count
    vm.count = 5
    console.log(vm.$data.count) // => 5
    
    // 反之亦然
    vm.$data.count = 6
    console.log(vm.count) // => 6
    
    
    #+RESULTS:
    

npm

npm install 将会执行package.json 的设定, 在IDAE里可以选中package.json 里的 build:prod字段,run

操作

vd 是vue里的data属性

vm 是vue里的mothods方法

ht 是html里的标签


{{vd}} 占位
v-text="vd" 替换
v-html="vd" 替换并渲染
v-bind:ht="vd" :ht="vd" 设置属性 可用3元表达式或者数据的元素对象指定 v-on:ht="vm" @ht="vm" on methode(可自定义) v-mode="vd" 只在表单中暴露vd,并操作
v-for="(item,index) in "vd"" vd时vue中可迭代元素或在对象
v-for="i in 10" 1,,,,,9
push 后加
unshift 前加
v-if 删除不显示的元素
v-show display 不显示的元素


生命周期


beforeCreate 加载vue系统构造,但是可以接触到Dom元素 created 加载自定义的data,mothods, filter..... beforeMounte 创建特性在内存 mounted 加载特性,渲染页面 beforeupdate 更改特性 updated 渲染更改的特性 beforedestroy 准备清除特性 destroy


component

1, 用extends编写template 2, 在component中编写template 3, 在vue 外部,script模块中编写template 4, 在vue的组件中使用变量和方法,必须在组件中用函数定义,

Mustache

{{item }} item von el can be here

v-bind

v-bind: kann verbunden werden mit id, href, key, für characters von DOM elements

multi class 动态绑定v-band

  1. 三目运算指定class
  2. 集合,可删除class,不可增加,不会被拦截
  3. 数组,可加可减

multi style 动态绑定v-band

  1. 三目运算指定style
  2. 集合,可删除style,不可增加, 不会被拦截
  3. 数组,可加可减

v-show

if v-show is false, the DOM element is already included, but will not be presented.

v-if

if v-if is false, the DOM element will be deleted

watch multiple value

watch(
  () => [PlasData.Amount_Package_Plasmid_1, PlasData.Concentration_Package_Plasmid_1],
  ([Amount_Package_Plasmid_1, Concentration_Package_Plasmid_1]) => {
    PlasData.Volume_Package_Plasmid_1 =  +((1/Concentration_Package_Plasmid_1)*Amount_Package_Plasmid_1).toFixed(2)
  })

reactive multiple value

const platedata :PlatedataType[]  = reactive([])
platedata.push({id:1, name:"6 Well", highlight: false, editable: true, show: false})

add such into keybindings.json for vscode, snippet for django-template { "key": "ctrl+y", "command": "editor.action.insertSnippet", "args": { "name": "trans" } }

Language


title: C

#+STARTUP: content

Program

Decimal to Binary Octal Hexdecimal char

#include <stdio.h>
int main( )
{
  int a = 80;
  printf("the input a is %d\n",a);
  printf("converse to 8 base is %#o\n", a);
  printf("converse to 16 base is %#X\n", a);
  printf("converse to char is %c\n", a);
  return 0;
}

Primzahl filter

#include<stdio.h> 
#include"math.h"
int main( )
{
  int i;
  int j;
  for (i = 2; i < 10; i++) {
    int temp = (int)sqrt(i);
    for (j = 1; j <= 1000; j++) {
      if (j != 1 && i%j == 0 ) {
        break;
      }else {
        if (j == temp) {
          printf("%d \n",i);
          break;
        }
      }
    }
  }
  return 0;
}

itoa

atoi, 如有非数字字符,就为0 itoa , 非ASCII标准函数库,看collection.

#include <stdio.h>
#include <stdlib.h>

char* itoa(int val, int base){
  static char buf[32] = {0};
  int i = 30;
  for(; val && i ; --i, val /= base)
    buf[i] = "0123456789abcdef"[val % base];
  return &buf[i+1];
}

int main(int argc, char *argv[])
{
  int a = 100;
  char* str = itoa(a, 8);
  printf("%s \n",str);
  return 0;

}

each time only reserive 3 agruments

  • Each time ask default 3 agreements, less is ok, the more will be ignored.
  • scanf("%s", a); can't deal with more agreements. the more will be read next time
  • scanf("%[^\n{=latex}]", a); can't deal with less agreements,

because without \n{=latex}, I don't know where to stop

  • scanf("c%",a); can use '\n{=latex}' and ' ' to determine the stop and number of agreements.
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
  while(1){
    char a[3][10] = {"", "", ""};
    char b[100];
    scanf("%[^\n]", b);
    printf("b is %s\n", b);
    int j = 0;
    int i = 0;
    do{
      int k = 0;
      do{
        a[j][k] = b[i];
        i++;
        k++;
      }while(b[i] != ' ');
      printf("a[%d] iooooos %s\n", j, a[j]);
      j++;
      i++;
    }  while (j<3);
    scanf("%*[^\n]"); scanf("%*c");
  }
//  return 0;
  }

SortingGiveNumbersWithExchangeSortedDirection

milisecond time

#include <sys/time.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

#define N 1000000

int current_timestamp() {
  struct timeval te; 
  gettimeofday(&te, NULL); // get current time
  int milliseconds = te.tv_sec*1000 + te.tv_usec/1000; // calculate milliseconds
  return milliseconds;
}

int main(int argc, char *argv[])
{
  float arr[N];
  float summation;
  int start, stop;
  for (int i = 0; i < N; ++i) {
    arr[i] = rand() % 100 / (float)100 ;
  }
  start = current_timestamp();
  for (int i = 0; i < N; ++i) {
    summation += arr[i];
  }
  stop = current_timestamp();
  printf("Summation is %f,  using time %d ", summation,  stop-start);
  return 0;
}


gcc task1_q1.c -o task1_q1
./task1_q1

Summation is 494979.375000,  using time 4 

Point&array

pointer assignment

int *c

only exits *c, if assige 1 to c, segment default

  int *c;
  printf("format string is %d,  %d, %d\n" , *c, c, &c);
  *c = 101;
  printf("format string is %d,  %d, %d\n" , *c, c, &c);#+end_src

#+RESULTS:
: format string is 1,  -1754099728, -1754099984
: format string is 101,  -1754099728, -1754099984

segment default for this
#+begin_src C :results output
  int *c;
  printf("format string is %d,  %d, %d\n" , *c, c, &c);
  c = 101;
  printf("format string is %d,  %d, %d\n" , *c, c, &c);

int * c = 100

only exit c, if access to *c, segment default

int *cc = 100;
printf("format string is  %d, %d\n" , cc, &cc);
cc = 101;
printf("format string is   %d, %d\n" , cc, &cc);

assign a address, all exits now

point to pass

void output(int *t){
  printf("%d\n", *t );
  (*t)++;
}

int c = 1;
printf("c : %d\n",c );
for (int i = 0; i< 10; i++){
  output(&c);
}
printf("c : %d\n",c );
void output(int t[2]){
  printf("%d\n", t[1] );
  (t[1])++;
  t[0] = 100;
}

int c[2] = {1,2};
printf("c[1] : %d\n",c[1] );
for (int i = 0; i< 10; i++){
  output(c);
}
printf("c[0] : %d\n",c[0] );
printf("c[1] : %d\n",c[1] );

reference to pass not to that

void output(int &t){
  printf("%d\n", t );
  t++;
}

int a = 10;
printf("a : %d\n",a );
for (int i = 0; i< 10; i++){
  output(a);
}
printf("a : %d\n",a );

char *ptr;

all exist

char *ptr ;
printf("format string %d is %s at %d \n" , *ptr, ptr, &ptr);
ptr = "lko";
printf("format string is %s \n" , ptr);

all exist

char *ptrr = "ok";
printf("format string %d is %s at %d \n" , *ptrr, ptrr, &ptrr);
ptrr = "lko";
printf("format string is %s \n" , ptrr);

pointer and array description

*p = a[n] p a


the first Value *p / p[0] *a / a[0] the n-th Value *(p+n)/ p[n] *a+n/ a[n] the first Address p / a / &a[0] the n-th Address p+n / &a[n]

在传递过程中, 数组的传递可以用指针来接受, 指针的传递可以用数组来接受,但必须是指针类型的数组

#include <iostream>
int main(){
  int a[]={1,2,3,4,5};
  int *p = a;
  printf("Print this hallo!\n");
  printf("for value\n");
  printf("%d\n",*p);
  printf("%d\n",*a);
  printf("%d\n",a[0]);
  printf("%d\n",p[0]);
  printf("nihao :%d\n",*(p+1));
  printf("%d\n",*a+1);
  printf("%d\n",a[1]+1);
  printf("%d\n",p[1]+1);
  printf("for address:\n");
  printf("%d\n",p);
  printf("%d\n",a);
  printf("%d\n",&a[0]);
  printf("%d\n",p+2);
  printf("%d\n",&a[2]);
  printf("%c\n","0123456789abcdef"[3]);
  char *list = "0123456789abcdef";
  printf("%s\n",&list[10]);
  return 0;
}

2orderPoint assignment to *

2 order Point assignment to (*a, a, &a)

#include <stdio.h>
void Point2order(int **a){
  printf("**a : %d\n",**a );
  printf("*a  : %d\n",*a );  
  printf(" a  : %d\n", a );
  printf("&a  : %d\n",&a );
  printf("\n");
  int *z = *a;
  printf("  int *z = *a : if z = *a\n");
  printf("z  : %d\n", z );
  printf("*a : %d\n", *a );
  printf("if *z = **a\n");
  printf("*z :%d\n", *z );
  printf("**a:%d\n",  **a );
  printf("\n");
  int *y = a;
  printf("  int *y = a : if y = a\n");
  printf("y  : %d\n", y );
  printf("a  : %d\n", a );
  printf("if *y = *a\n");
  printf("*y : %d\n", *y );
  printf("*a : %d\n",  *a );
  printf("\n");
  int *x = &a;
  printf("  int *x = &a : if x = &a\n");
  printf("x  : %d\n", x );
  printf("&a : %d\n", &a );
  printf("if *x = *(&a)\n");
  printf("*x : %d\n", *x );
  printf("*&a: %d\n",  *(&a) );
}
int main(int argc, char *argv[])
{

  int aa[] = {10,20,30};
  int *a = aa;
  Point2order(&a);
  return 0;
}
**a : 10
*a  : 1886852988
 a  : 1886852976
&a  : 1886852904

  int *z = *a : if z = *a
z  : 1886852988
*a : 1886852988
if *z = **a
*z :10
**a:10

  int *y = a : if y = a
y  : 1886852976
a  : 1886852976
if *y = *a
*y : 1886852988
*a : 1886852988

  int *x = &a : if x = &a
x  : 1886852904
&a : 1886852904
if *x = *(&a)
*x : 1886852976
*&a: 1886852976

Important

#include <stdio.h>
int main(){
  int a[3][4]={0,1,2,3,4,5,6,7,8,9,10,11};
  int(*p)[4];
  int i,j;
  p=a;
  for(i=0; i<3; i++){
    for(j=0; j<4; j++) printf("%2d  ",*(*(p+i)+j));
    printf("\n");
  }
  printf("\n");

  int *m[4] = {a[0],a[1],a[2],a[3]};
  for(i=0; i<3; i++){
    for(j=0; j<4; j++) printf("%2d  ",*(*(m+i)+j));
    printf("\n");
  }

  return 0;
}
0   1   2   3  
4   5   6   7  
8   9  10  11  

0   1   2   3  
4   5   6   7  
8   9  10  11  

* assignment to 2orderPoint

char / int 数组/指针数组 to 二级指针 [] > * > + *(p+1)== p[1] and *p+1 == (*p)+1

#include <stdio.h>
void funaa(char **p){
  printf("address mani after 2\n");
  printf("funaa : %c\n", *p[0] );
}
void funbb(int **p){
  printf("address mani after 2\n");
  printf("funbb : %d\n", *p[0] );
}
void funa(char **p){
  printf("value mani: \n");
  printf("funa: the first %c\n", **p );
  printf("funa: the third %c\n", *(   (*p+1)    +1)      );
  char *pa = *p+2;
  funaa(&pa);
  }
void funb(int **p){
  printf("\n");
  printf("value mani: \n");
  printf("funb: the first %d\n", **p );
  printf("funa: the third %d\n", *(   (*p+1)    +1)       );
  int *pa = *p +2;
  funbb(&pa);
}

void funChar2OrderPoint(char ** p){
  printf("\n");
  printf("point arrar[0][0]:%c\n", *( *(p+0) +0)           );
  printf("point arrar[0][1]:%c\n", p[0][1]                 );
  printf("point arrar[0][2]:%c\n", *( *(p+0) +2)           );
  printf("point arrar[1][0]:%c\n", *( *(p+1) +0)           );
  printf("point arrar[1][1]:%c\n", *( *(p+1) +1)           );
  printf("point arrar[1][2]:%c\n", *( *(p+1) +2)           );
  printf("point arrar[2][0]:%c\n", *( *(p+2) +0)           );
  printf("point arrar[2][1]:%c\n", *( *(p+2) +1)           );
  printf("point arrar[2][2]:%c\n", *( *(p+2) +2)           );
}
void funInt2OrderPoint(int ** p){
  printf("\n");
  printf("point arrar[0][0]:%d\n", *( *(p+0) +0)           );
  printf("point arrar[0][1]:%d\n", *( *(p+0) +1)           );
  printf("point arrar[0][2]:%d\n", p[0][2]                 );
  printf("point arrar[1][0]:%d\n", *( *(p+1) +0)           );
  printf("point arrar[1][1]:%d\n", *( *(p+1) +1)           );
  printf("point arrar[1][2]:%d\n", *( *(p+1) +2)           );
  printf("point arrar[2][0]:%d\n", *( *(p+2) +0)           );
  printf("point arrar[2][1]:%d\n", *( *(p+2) +1)           );
  printf("point arrar[2][2]:%d\n", *( *(p+2) +2)           );
}
int main(int argc, char *argv[])
{
  /* char 一维数组转二级指针 */
  char a[] ="1234567";
  char *pa = a;
  funa(&pa);
  /* int 一维数组转二级指针 */
  int b[] = {1,2,3,4,5,6,7};
  int *pb = b;
  funb(&pb);
  /* char 指针数组转二级指针 */
  char a1[] ="123";
  char a2[] = "456";
  char a3[] = "789";
  char *chara [] = {"123", "456", "789"};
  char **poa = chara;
  funChar2OrderPoint(poa);
  printf("\n");
  printf("%s\n", *chara+2 );
  printf("%s\n", *chara+1 );
  printf("%s\n", *chara   );
  printf("\n");
  printf("%s\n", chara[0] );
  printf("%s\n", chara[1] );
  printf("%s\n", chara[2] );
  printf("\n");
  printf("%c\n",      chara[1][2]         );
  printf("%c\n",*(    chara[1]      +2)   );
  printf("%c\n",*(   *(chara+1)     +2)   );

  /* int 指针数组转二级指针 */
  int b1[] = {1,2,3};
  int b2[] = {4,5,6};
  int b3[] = {7,8,9};
  int *intb [3] = {b1, b2, b3};
  int **pob = intb;
  funInt2OrderPoint(pob);
  printf("\n");
  printf("如果打开评论,可以执行,但是会报警告,结果是对应元素的地址\n");
  // printf("%d\n", *intb+2 ); //&3
  // printf("%d\n", *intb+1 ); //&2
  // printf("%d\n", *intb   ); //&1
  // printf("\n");
  // printf("%d\n", intb[0] );  //&123
  // printf("%d\n", intb[1] );  //&456
  // printf("%d\n", intb[2] );  //&789
  printf("\n");
  printf("%d\n",      intb[1][2]         );
  printf("%d\n",*(    intb[1]      +2)   );
  printf("%d\n",*(   *(intb+1)     +2)   );

  return 0;
}

Summary

           1                 3              2              4

Form char *argv[] int *a3[] int *a2 int a4[][2] 传递时时参 argv a3 &a2 a4 接收时形参 char **p1 int **p3 int **p2 int(*p4)[2] argv[1][2] a3[0][1] a2[2] a4[1][0] p1[1][2] p3[0][1] p2[0][2] p4[1][0]


 \*(\*(p+1)+2)   \*(\*(p+0)+1)   \*(\*(p+0)+2)   \*(\*(p+1)+0)

#include <stdio.h>

int main(int argc, char *argv[])

{ 
  char **p1 = argv;
  printf("%c \n", argv[1][2]   );
  printf("%c \n", p1[1][2]     );
  printf("%c \n", *(*(p1+1)+2) );


  int b2[] = {1, 2, 3, 4, 5};
  int *a2 = b2;
  int **p2 = &a2;
  printf("%d \n", a2[1]         );
  printf("%d \n", *(a2+1)       );
  printf("%d \n", p2[0][1]      );
  printf("%d \n", *(*(p2+0)+1)  );

  int m[] = {1,2};
  int n[] = {3,4};
  int *a3[] = {m, n};
  int **p3 = a3;
  printf("%d \n", a3[0][1]      );
  printf("%d \n", p3[0][1]      );
  printf("%d \n", *(*(p3+0)+1)  );

  return 0;

  int a4[][2]  ={{1,2},{3,4}};
  int (*p4)[2] = a4;
  printf("%d \n", a4[1][0]      );
  printf("%d \n", p4[1][0]      );
  printf("%d \n", *(*(p4+1)+0)  );

}


Polymorphism

C++ 先生成基类实列后再生成子类实例并指向

需要借助虚函数来实现对相应多态函数的调用,在函数前加上virtual

#include <iostream>
using namespace std;

class Animal
{
public:
  Animal();
  virtual run();
};
Animal::Animal(){};
void Animal::run(){cout <<"Animal is running"<<endl;}

class Dog : public Animal
{
public:
  Dog();
  virtual run();
};
Dog::Dog(){};
void Dog::run(){cout <<"Dog is running"<<endl;}

Animal *p = new Animal;
p->run();
p = new Dog;
p->run();
//此时的p就是多态变量,但是只有这个变量先由基类生成,再指向子类
//反之时不能的

Python 可基可子

class Animal(object):
    def __init__(self):
        self.name ='Animal name'
    def run(self):
        print('Animal is running')

class Dog(Animal):
    def __init__(self):
        self.name ='Dog name'
    def run(self):
        print('Dog is running')

# Polymorphism, all Class or instance will be checked the best passing
# mothode or character
def run_twice(a):
    a.run()
def name(b):
    print(b.name)

ani = Animal()
ani.name
ani.run()

ani = Dog()
ani.name
ani.run()

## ani 可以先有基类实现再多态映射到子类,也可以反向实现

Python 3.7.4 (default, Aug 13 2019, 20:35:49) 
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
Animal is running
Dog is running
Cat is running
Dog is running
Animal name
Dog name
Dog name
python.el: native completion setup loaded

Java 子类实列指向父类引用

在向上转型后,就可以调用在所有子类中的同名函数

class Figure {
    double dim1;
    double dim2;
    Figure(double d1, double d2) {
        // 有参的构造方法
        this.dim1 = d1;
        this.dim2 = d2;
    }
    double area() {
        // 用于计算对象的面积
        System.out.println("父类中计算对象面积的方法,没有实际意义,需要在子类中重写。");
        return 0;
    }
}

class Rectangle extends Figure {
    Rectangle(double d1, double d2) {
        super(d1, d2);
    }
    double area() {
        System.out.println("长方形的面积:");
        return super.dim1 * super.dim2;
    }
}

class Triangle extends Figure {
    Triangle(double d1, double d2) {
        super(d1, d2);
    }
    double area() {
        System.out.println("三角形的面积:");
        return super.dim1 * super.dim2 / 2;
    }
}

public class Test {
    public static void main(String[] args) {

        Figure figure = new Rectangle(9, 9);
        System.out.println(figure.area());
        System.out.println("===============================");
        figure = new Triangle(6, 8);
        System.out.println(figure.area());
        System.out.println("===============================");
        figure = new Figure(10, 10);
        System.out.println(figure.area());

    }
}

Scanf

input matching for multi input Scanf()

可以直接从控制台接受8, 10, 16 进制的数 只有当控制字符串以格式控制符(%d、%c、%f) 开头时,键入的input才会忽略换行符, 否则输入的空白符就不能忽略了,它会参与匹配过程

清空每次输入的所有缓存

scanf("%*[^\n{=latex}]"); scanf("%*c");

Scanf(%{*}{width}type)

其中,{ } 表示可有可无。各个部分的具体含义是: type表示读取什么类型的数据,例如 %d、%s、%[a-z]、%[^\n{=latex}] 等;type 必须有。 width表示最大读取宽度,可有可无。 *表示丢弃读取到的数据,可有可无。

hits

malloc for 2 diamesion

char ** commands; commands = (char **)malloc(NUMOFCOM * sizeof(char *)); for (int n = 0; n < NUMOFCOM; n++) commands[n] = (char *)malloc(sizeof(char) * COMLONG);

reference

1. 如果在函数体中修改了形参的数据,那么实参的数据也会被修改,从而拥有“在
   函数内部影响函数外部数据”的效果
2. 不能返回局部数据(例如局部变量、局部对象、局部数组等)的引用,因为
   当函数调用完成后局部数据就会被销毁,有可能在下次使用时数据就不存在
   了
3. 给引用添加 const 限定后,不但可以将引用绑定到临时数据,还可以将引用
   绑定到类型相近的数据,这使得引用更加灵活和通用,它们背后的机制都是
   临时变量

class

1. 基类中的 protected 成员可以在派生类中使用,而基类中的 private 成员不能
   在派生类中使用
2. 只有一个作用域内的同名函数才具有重载关系,不同作用域内的同名函数是
   会造成遮蔽
3. 如果基类的成员变量被派生类的成员变量遮蔽, 基类成员仍会在实例化时被
   创建,也可通过域解析符来访问。
4. 构造函数会被逐级的显示或者默认的在派生类中被调用,并且可以被重载
5. C++ 可以多继承不同的类(多继承和重继承),注意其构造函数的调用和成
   员名称冲突,但是可以用域解析符来指明调用
6. 即使是类的private成员,仍能通过创建的对象的地址偏移或者直接利用指针
   进行访问。(有点花里胡哨的)
7. C++中虚函数的唯一用处就是构成多态
8. 引用不像指针灵活,指针可以随时改变指向,而引用只能指代固定的对象

const

const 的作用在C++中和宏很像#defind
函数中const,修饰变量后可以将传入的参数,强制转换为设定的
初始化 const 成员变量的唯一方法就是使用参数初始化
类中的const, 变量,函数, 类, 只能互相承
重要:在头文件中用const修饰全部变量后,就可以多次被引入了而不会出现重
复定义的错

static

statis 变量, 函数,全部对象可以共用,访问,无this指针。不能调用普通变量和函数类
static 多被用来计数,可以在外部被改

GDB

can be done in terminal or in Emacs, recommend later one


b add break point run start the program run argv if argv needed n next l list source code 10 lines p print variables s go into functions ignore pass the break point q exit set set variable


in emacs, if scanf, the input can not be given in gdb buffer. if it comes to scanf, go to the I/O buffer, and input the value , go back to gdb buffer, just next

Compile

There are four different kinds of Methods to compile a source file.

Makefile

There is a folder called Makefile, into this folder, and call "make" in terminal, don't forget "make clean" to clean it.

Terminal Compile

In pthread~andpid~ folder with terminal with "g++/gcc file.c -o file", and then "./file" to call it

Emacs Compile

Also in pthread~andpid~ folder, open the resource code with Emacs, and then M-x compile(C-z k) call it in minibuffer with : "gcc -pthread create~pthread~.c -o create~pthread~ && ./create~pthread~"

Literatur programmierung

pass the agruments to program

在src block 中提前定义:var a = 3
javac test.java &&  echo 1 |java test 可以将1向StdInt传入
gcc test.c && echo 1 | ./a.out 可以将1向scanf("%d", &a)传入的a

Beispile

#+header:  :var input=23 :var b1 = 0 :var b2=1 :var b3=3
int b[] = {b1, b2, b3};
  printf("niiiiilhakkko\n");
  printf("%d\n", input);
  printf("%d\n", b2);
  for(int i = 0; i<3;i++){
    printf("%d", b[i]);
   }
niiiiilhakkko
23
1
013

reference and Pointer in SRC


title: Typescript

#+startup: content

basic

function greeter(person: string) {
    return "Hello, " + person
}
let user = "Yee"
console.log(greeter(user))
Hello, Yee
function greeter(person: string) {
    return "Hello, " + person
}
"use strict";
let user = [2, 39]
console.log(greeter(user))
../../../../tmp/babel-cIibwh/ts-src-IRbM7W.ts(6,21): error TS2345: Argument of type 'number[]' is not assignable to parameter of type 'string'.
Hello, 2,39
class User{
    Fristname:string
    Lastname:string
    Fullname:string

    constructor(firstname:string, lastname:string){
        this.Fristname = firstname
        this.Lastname = lastname
        this.Fullname = this.Fristname+this.Lastname
    }
}
interface Person{
    Fristname:string
    Lastname:string
}

function Greeter(Person){
    return "hello, "+Person.Fristname + Person.Lastname
}
var user = new User("li", "san")

console.log(Greeter(user))

../../../../tmp/babel-cIibwh/ts-src-DPsbOA.ts(17,18): error TS7006: Parameter 'Person' implicitly has an 'any' type.
hello, lisan

callback

const n: number = 10
let qual = n => n*n;  
let m = (() => {
    console.log('nidh', n, qual(4))
    return 9
})()
console.log(m)

../../../../tmp/babel-KUfP9t/ts-src-HiNQhf.ts(2,12): error TS7006: Parameter 'n' implicitly has an 'any' type.
nidh 10 16
9
let jj = (
    (msg , didi) => {
        console.log(msg);
        didi(msg);
        return 9
    }
)
( "kdiikkjkjk",
  msg => {
      console.log(msg);
  }
)

console.log(jj)
../../../../tmp/babel-KUfP9t/ts-src-SG7pDT.ts(11,3): error TS7006: Parameter 'msg' implicitly has an 'any' type.
kdiikkjkjk
kdiikkjkjk
9

Generic

withour generic

function createArray(value: any, count: number): any[] {
  const arr: any[] = []
  for (let index = 0; index < count; index++) {
    arr.push(value)
  }
  return arr
}

const arr1 = createArray(11, 3)
const arr2 = createArray('aa', 3)
console.log(arr1)
console.log(arr2)
console.log(arr1[0].toFixed(), arr2[0].split(''))
[ 11, 11, 11 ]
[ 'aa', 'aa', 'aa' ]
11 [ 'a', 'a' ]

with generic

function createArray2 <T> (value: T, count: number):T[] {
  const arr: Array<T> = []
  for (let index = 0; index < count; index++) {
    arr.push(value)
  }
  return arr
}
const arr3 = createArray2<number>(11, 3)
console.log(arr3[0].toFixed())
// console.log(arr3[0].split('')) // error
const arr4 = createArray2<string>('aa', 3)
console.log(arr4[0].split(''))
// console.log(arr4[0].toFixed()) // error
11
[ 'a', 'a' ]

advanced example

interface IbaseCRUD <T> {
  data: T[]
  add: (t: T) => void
  getById: (id: number) => T

}

class User {
  id?: number; //id主键自增
  name: string; //姓名
  age: number; //年龄

  constructor (name, age) {
    this.name = name
    this.age = age
  }
}

class UserCRUD implements IbaseCRUD <User> {
  data: User[] = []

  add(user: User): void {
    user = {...user, id: Date.now()}
    this.data.push(user)
    console.log('保存user', user.id)
  }

  getById(id: number): User {
    return this.data.find(item => item.id===id)
  }
}


const userCRUD = new UserCRUD()
userCRUD.add(new User('tom', 12))
userCRUD.add(new User('tom2', 13))
console.log(userCRUD.data)
../../../../tmp/babel-VDC0rp/ts-src-ub8Ktp.ts(13,16): error TS7006: Parameter 'name' implicitly has an 'any' type.
../../../../tmp/babel-VDC0rp/ts-src-ub8Ktp.ts(13,22): error TS7006: Parameter 'age' implicitly has an 'any' type.
保存user 1629717666420
保存user 1629717666424
[
  { name: 'tom', age: 12, id: 1629717666420 },
  { name: 'tom2', age: 13, id: 1629717666424 }
]

interface

class User{
    Fristname:string
    Lastname:string
    Fullname:string

    constructor(firstname:string, lastname:string){
        this.Fristname = firstname
        this.Lastname = lastname
        this.Fullname = this.Fristname+this.Lastname
    }
}
interface Person{
    Fristname:string
    Lastname:string
}

function Greeter(Person){
    return "hello, "+Person.Fristname + Person.Lastname
}
var user = new User("li", "san")

console.log(Greeter(user))

../../../../tmp/babel-VDC0rp/ts-src-kkk0v4.ts(17,18): error TS7006: Parameter 'Person' implicitly has an 'any' type.
hello, lisan

collection

var nn = 10.00002
console.log(+nn.toFixed(2))
10

title: Scala

#+STARTUP: overview
println("niho")
println("hi")

title: Lisp

#+startup: content

root

S-express can be atmo or list car : get the first S-express cdr : get the rest list cons : need a S-express and a list : put the first S-express into the second list (null? l) if l is null? (atom? l) if l is atmo? (member? ele list) (rember ele list)

command

execute


command explain C-c C-e result in minibuffer C-j result under the cursor M-x ielm in elisp interactive mode


List

(concat "abd" "def")
(+ 34 9)

(substring "0123456789" 2 8)

(setq Emacs 'My-favour)

(message "Am today %s I start to learn emacs %d " "niaho" 09)
;"Am today niaho I start to learn emacs 9 "
(message "He saw %d %s"
(- fill-column 32)
(concat "red "
(substring
"The quick brown foxes jumped." 16 21)
" leaping."))
;"He saw 38 red foxes leaping."
(setq trees '(pine fir oak maple)
           herbivores '(gazelle antelope zebra))

Evaluation


(buffer-file-name)
(setq a 300)
(* 34 67 45

)

Buffer

(buffer-name)

(current-buffer)

(other-buffer)

(switch-to-buffer (other-buffer))

(buffer-size)

(point)

(point-min)

(point-max)

(defun multipy-by-seven (number)
"Multipy NUMBER by seven"
(* 7 number))

(multipy-by-seven 4)

(defun multipy-by-seven (number))

(interactive "p")

(message "the result is %d" (* 7 number))

let and let *

let define the local variable

(defun circle-area (radix)
  (let ((pi 3.1415926)
        area)
    (setq area (* pi radix radix))
    (message "直径为 %.2f 的圆面积是 %.2f" radix area)
    ))
(circle-area 5)

let* define local variable, which can be immediately used

(defun circle-eara (radix)
  (let* ((pi 3.1415926)
         (area (pi*radix*radix))))
    (message "直径为 %.2f 的圆面积是 %.2f" radix area))
(circle-area 6)

Special Form

defun

(defun name-of-function (argument-list) "documentation..." body...)

let

(let ((zebra "stripes") (tiger "fierce")) (message "One kind of animal has %s and another is %s." zebra tiger))

if

(defun my-max (a b)
  (if ( > a b)
    (message "aaaaa")
    (message "bbbbb")
    ))
(my-max 3 0)  

(if true-or-false-test action-to-carry-out-if-the-test-returns-true)

if-then

(if true-or-false-test action-to-carry-out-if-the-test-returns-true action-to-carry-out-if-the-test-returns-false)

(if 4 'true 'false)

(if nil 'true 'false)

save-excursion

(message "We are %d characters into this buffer." (save-excursion (- (point) (goto-char (point-min)) (point))))

2-36 arbitrary base

#36re
#36r1
#36ra
#36ru
#36rk

code

char count

(defun cheap-count-words()
  (interactive)
  (let ((words 0))
    (goto-char (point-min))
    (while (forward-word)
      (setq words (1+ words)))
    (message (format "Words is Buffer : %s" words))
    words)
  )

Emacs lisp programm

file management

read file :: insert-file-contents and copy file :: write-region

;;read file and print out
(defun read-file-as-lines (file-path)
  (with-temp-buffer
    (insert-file-contents file-path)
    (split-string (buffer-string) "\n" t)))

(read-file-as-lines "~/Desktop/110.py")

;;read file and copy to another
(defun copy-file-to-file (fromfile tofile)
  (with-temp-buffer
    (insert-file-contents fromfile)
    (setq copy-test-path tofile)
    (write-region (point-min) (point-max) copy-test-path)
    (write-region "new  content" nil copy-test-path t)))

(copy-file-to-file "~/Desktop/110.py" "~/Desktop/112.py")




Function in orgmode

(+ 45 65)
(defun do-some-math(x y)
  (* (+ x 20)
     (- y 10) ) )
(defun multipy-many  (x &rest operands)
  (dolist (operand operands) 
    (when operand 
      (setq x (* x operand)))) x)

interactive function als commands

(defun my-first-command()
(interactive)
(message "Hey , it works") )


title: Java

#+STARTUP: overview

java Settings

StdInt echo with stdlib

// class test
// {
//     public static void main(String[] args) {
//         StdOut.print("Type an int: ");
//         int a = StdIn.readInt();
//         double b = StdIn.readDouble();
//         StdOut.println("Your int was: " + a);
//         StdOut.println("Your double was: " + b);
//         StdOut.println();
//     }
// }

download : stdlib herunterladen

add this to classpath: export CLASSPATH=.:/home/sx/Documents/Java/classpath/*
emacs should started by terminal, in order to inherit the envirement variables
M-x compile
javac test.java && echo 2 3.9803 |java test

execute a single java file in Emacs in a packages

cd ./../../../../ && javac -d . com/jimmysun/algorithms/chapter1_1/Ex37.java  && java com/jimmysun/algorithms/chapter1_1/Ex37

Entpacken

jar xvf date.jar

Notes

%o %d %x %f Integer.toBinaryString(a) 用补码来记录正数和负数,0 to 127 to -128 to -1 to 0 ..... 小数浮点型float要加f, 否则是double

find JAVA~HOME~

which java just a link

which java 

in Linux console with bash:

dirname $(dirname $(readlink -f $(which javac)))

in Linux use jkd :

java -XshowSettings:properties -version 2>&1 > /dev/null | grep 'java.home'

package

在同一类中,可以直接调用彼此的方法和属性,在同一包中,如果要调用其他类 的方法,要指明类的地方

jar execution

java -jar 执行jar包,不须指定启动类的入口,程序指定了main class 的入口 java -jar xxx.jar

java -cp 执行jar包,须要指定启动类的入口,程序没有指定main class 的入口 java -cp /target/xxxx.jar com.mycompany.app.App

IDEA generate jar

add all plugins to project

<project>
      .........
      <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>2.3</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <transformers>
                                <transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

File -> Project structur -> Artifacts -> + Build -> Build Artifacts -> build

Java programmierung

Sammlungen

基本数据类型传数值. 而引用传地址 String --> Int Integer.parseInt <---> String.valueOf() String --> char[] string.toCharArray() <---> new String(array) String --> byte[] str.getBytes() <----> new String(byte)

StringBuffer :: 线程安全, 可变

StringBuilder :: 线程不安全, 可变

Tpye Conversion Error

  class Type_Conversion_Error
  {
      public static void main(String[] args)
      {
          char a = 'c';
          System.out.printf("%c\n", a);

          a++ ;      // right . because 'c'+1 is a  ASCII , has no type
          System.out.printf("%c\n", a);

//          a = a+1;  // wroung . because a+1 is a variable, and has type
          System.out.printf("%c\n", a);
      }
  }

String

  class Stringcon
  {
      public static void main(String[] args)
      {
          String s = "hallo";  // 字面量
          String ss = new String("hallo");
          System.out.println(s.hashcode());
          System.out.println(s);
          System.out.println(ss);
      }
}
hallo
hallo

s:: 是用private final char[] 储存的,不能更改,可用hash码检验 字面量的String在常量区, 不可改, 相同常量,只存一份 如果有拼接,则在堆里重新开辟空间,相当于new

ss:: new 的String("hallo")创建了两个对象,一个new在堆,一个hallo 常量字符串 ,

Random~uniform~

import java.util.*;
class StdRandom_uniform
{
    public static void main(String[] args)
    {
    int a = StdRandom.uniform(10);
    System.out.println(a);
    }
}


toBinaryString & toString

class Binary
{
    public static void main(String[] args)
    {
    int  x = Integer.MAX_VALUE;
    System.out.println(x);
    String s = Integer.toBinaryString(x);
    System.out.println("0"+s);

    int y = x +1;   
    String ss = Integer.toBinaryString(y);  
    System.out.println(y);
    System.out.println(ss);

    }
}


null class

return its reference


class null_class
{
    public static void main(String[] args)
    {
        P p = new P();
        System.out.println(p);
    }
}

class P{
    public P(){
    }
}

Array

find a element in array and print out


class test
{
    public static void main(String[] args)
    {
        int N = args.length;
        int [] f = new int [N];   
        int q = StdIn.readInt();
        for (int i = 0; i < N; i++) {
            f[i]= Integer.parseInt(args[i]);
        }
        int k = search(f, q, 0, N);
        System.out.println("the search is " + k);
    }
    public static int search(int [] f, int q, int lo, int hi){
        if (lo >= hi) {
            return -1;
        }
        int mid = (lo + hi)/2;    
        int median = f[mid];
        if (q > median) {
            return search(f, q, mid+1, hi);
        }else if (q < median) {
            return search(f, q, lo, mid-1);
        }else{
            System.out.println(f[mid]);
            return f[mid];
        }
    }
}

clone array

class copyarray
{
    public int n;  
    public int [] a1 = new int [n] ;
    public int [] a2 = new int [n];
    public static void main(String[] args)
    {
        int [] a = {1,2,3,4,5,6,7};
        copyarray array = new copyarray(a);
        array.show();
    }

    public copyarray(int [] array){
        this.n = array.length;
        this.a1 = array;
        this.a2 = (int []) array.clone();
    }

    public void show(){
        for (int i = 0; i < a1.length; i++) {
            System.out.printf(a1[i]+" ");
        }
        System.out.println();

        a1[0] =0;
        System.out.println("only change the first element of a1");
        for (int i = 0; i < a1.length; i++) {
            System.out.printf(a1[i]+" ");
        }
        System.out.println();

        System.out.println("a2 will still the same");
        for (int i = 0; i < a2.length; i++) {
            System.out.printf(a2[i]+" ");
        }
    }
}

generate a random array

import java.util.*;
class rarray
{
    public static void main(String[] args)
    {

    int n = Integer.parseInt(args[0]);
    int array [] = randomarray(n);

    }

    static int [] randomarray(int n){
    int array [] = new int [n];
    for (int i = 0; i < n; i++) {
        array[i] = i;
    }

    Random r = new Random();

    for (int i = 0; i < n; i++) {
        int a = r.nextInt(n-i);
        int tmp = array[n-i-1];
        array[n-i-1]= array[a];
        array[a] = tmp;
    }

    for (int i = 0; i < n; i++) {
        System.out.printf(array[i] + " ");
    }

    return array;
    }
}



2Darray of class Instance

class multiDiaClass
{
    public static void main(String[] args) 
    {
        Emp [][] emp = new Emp[3][3];
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                emp[i][j] = new Emp();
                System.out.println(emp[i][j].toString());
            }
        }
    }
}
class Emp{
    static int n = 0;

    public Emp(){
        this.n = n;
        n++;
    }

    public String toString(){
        return "In this class  n is " + this.n + " ";
    }
}

匿名类

在形参内,new 一个类,不用赋予引用名,并可以重写内部方法

Annotation

修饰方法,可以有成员变量,default

元注解


@Retention Source, Class, RunTime @Target 确定可修饰的类型 @Documented 生成Javadoc文档


HashMap

数组,链表,红黑树 1, 如果key的hash没有重复,则放入 2,如果hash有相同,比较key值,无重复也放入 3,如果key有重复,则改变该value

Generic

对一个对象设定某一类别,确保类型安全

Collections

比较与数组,优势很大 contains(obj) 会调用obj的equals方法,对于自定义的类,要重写该类的equals。 Iterator hasNext next()

Lambda

实现了抽象方法(接口)的具体实例化

equals and ==

== 对与基本类型,比较值, 对于引用类型来说是比较的是引用是否一样 equals 如无重写则和== 一样,如果重写,则按照重写,一般比较个特性内容是否一样

函数式接口

只有一个抽象方法,可以使用lambda简化很多。

方法引用

Lambda表达式的简化, 当对于Lambda表达式的操作已经有现成的实现方法后,调用此方法 1, 对象::非静态方法(实例方法) 2, 类:: 静态方法 3, 类::非静态方法 Cosumer 有唯一方法 accept() Supplier有唯一方法 get()

比较

Comparable

要对自定义的类按照某个特性自然排序, 可以在该类中实现此接口,并重写CompareTo方法 返回 1, 0, -1

Comparator

特制某种临时的排序方式,可在 形参的类变量中用匿名类来重写Compare方法

reflection

动态的Reflction API 可以获得对象的任意内容,并加以操作 通过Class类类创建实例 getConstructor getClardedMethod

用途:在运行时才决定的类创建,带有动态语言的特征

class test
{
    public static void main(String[] args) throws Exception
    {

    Class cls1 = String.class;
    System.out.println(cls1.hashCode());

    String s = "Hello";
    Class cls2 = s.getClass();
    System.out.println(cls2.hashCode());


    Class cls3 = Class.forName("java.lang.String");
    System.out.println(cls3.hashCode());

    }
}

ArrayList

import java.util.ArrayList;
class ArrayListl
{
    public static void main(String[] args) 
    {
        ArrayList<String> list = new ArrayList<>();
        list.add("niahoma");
        System.out.println(list);

    }

}

interface

需要被实现,以添加某些接口设定特定的功能

abstract class 抽象类

抽象类中的抽象方法不能实现,只能申明,也不能实列化 只有在其子类中实现后,才能使用

可以用来作接口 需要被继承,获得主体功能,但是可以被重写和添加自己需要的特定功能 如果有一个抽象方法未被重写,就只能保持为抽象类

intern class 内部类

内部类可以访问外部类的成员和方法,反之不行 静态类要依靠外部类的实列化对象来实列化

static class 静态类

可以直接实列化 也可以直接调用,例如Math.abs(-2)

Stream

.Stream .Parallelstream stream.of stream.interator stream.generate .filter .limit .skip .distinct .map .flatMap .sorted() .sorted(lambda expression) .anyMatch .allMatch .noneMatch .findFirst .findAny .count .min .max .ForEach() .reduce()

多肽

概念

父类引用指向子类实体对象 当调用时,如果指向的子类有相同名的方法,执行的是指向子类的方法 父类引用: 作形参 子类实体对象: 作实参

不适用于属性

重写

编译时: 程序内,同函数名,不同输入变量

重载

运行时: 类内,同方法名,不同输入变量

重调

执行时:(invoke) 库内,同方法名,不同输入变量 toString

IO

file

字节流:图片,视频 字符流:

Stream


抽象基类 节点流(文件流) mehthod InputStream FileInputStream 非文本 字节流 read(byte[] buffer) OutputStream FileOutputStream 非文本 字节流 write(byte [] buffer,0, len) Reader FileReader 文本文件:字符流 read(char [] cbuf) Writer FileWriter 文本文件:字符流 write(char [] cbuf, 0, leng)



抽象基类 缓冲流(处理流) mehthod InputStream BufferedInputStream read(byte[] buffer) OutputStream BufferedOutputStream write(byte [] buffer,0, len) Reader BufferedReader read(char [] cbuf) Writer BufferedWriter write(char [] cbuf, 0, len)


With throws can't close the stream certainly, if the Exception occers after the open, it can't close it anymore

import java.io.File;
import java.io.FileReader;
class FileRead
{
    public static void main(String[] args) throws Exception
    {
        File file = new File("c.org");
        System.out.println(file.getAbsolutePath());

        // java.io.FileReader fr = new java.io.FileReader(new java.io.File("c.org"));
        //java.io.FileReader fr = new java.io.FileReader(file);
        FileReader fr = new FileReader(file);

        // int data = fr.read();
        // while(data != -1){
        //     System.out.print((char)data);
        //     data = fr.read();
        // }
        int data;
        while((data = fr.read()) != -1){
            System.out.print((char)data);
        }

        fr.close();
    }
}

this the a great

import java.io.File;
import java.io.FileReader;
class FileReadtry
{
    public static void main(String[] args)
    {
        FileReader fr = null;
        try {
            File file = new File("c.org");
            System.out.println(file.getAbsolutePath());
            fr = new FileReader(file);
            int data;
            while((data = fr.read()) != -1){
                System.out.print((char)data);
            }
        }
        catch (Throwable e) {
            System.out.println("Error " + e.getMessage());
            e.printStackTrace();
        }finally{
            try {
                if (fr != null)
                    fr.close();
            }
            catch (Throwable e) {
                System.out.println("Error " + e.getMessage());
                e.printStackTrace();
            }
        }
    }
}

read with char[]

import java.io.File;
import java.io.FileReader;
class FileReadchar
{
    public static void main(String[] args)
    {
        FileReader fr = null;
        try {
            File file = new File("c.org");
            System.out.println(file.getAbsolutePath());
            fr = new FileReader(file);

            char [] cbuf = new char[10];
            int len;
            while((len = fr.read(cbuf)) != -1){
                for (int i = 0; i < len; i++) {
                    System.out.print(cbuf[i]);
                }
            }
        }
        catch (Throwable e) {
            System.out.println("Error " + e.getMessage());
            e.printStackTrace();
        }finally{
            try {
                if (fr != null)
                    fr.close();
            }
            catch (Throwable e) {
                System.out.println("Error " + e.getMessage());
                e.printStackTrace();
            }
        }
    }
}

Josephus-Problem

// javac Josehus.java && java Josehus 10 8
//there are two difference methode, one is with count methode and one is recursive

import java.util.ArrayList;
import java.util.List;
import java.util.*;

class Josehus
{
    static int run = 0;     // to count weiter, again and agina
    static int dis = 0;    //how many time are the list thougth counted
    static int count = 1;   // how many element are finish

    public static void main(String[] args)
    {
    if (args.length != 2 ) {
        System.out.println("please only give two agreements");
        return ;
    }
    int length = Integer.parseInt(args[0]);
    int step = Integer.parseInt(args[1]);
    List jose1 = josePermutation(length, step);
    for (int i = 0; i < jose1.size(); i++) {
        System.out.printf("%d ",jose1.get(i));
    }
    }
    static List josePermutation(int length, int step)
    {
        int [] circle = new int [length];
        for (int i = 0; i < length; i++) {
            circle[i] = i+1;
        }
        List<Integer> Folge = new ArrayList<Integer>();
        do {
            if(circle[run%length] != 0)
            {
                if ((run+1-dis)%step == 0) {
                Folge.add(circle[run%length]);
                count++;
                circle[run%length] = 0;
                }
                run++;
                continue;
            }
            run++;
            dis++;
        } while (count <= length);
        return Folge;
    }
}

Interview java

1. JDK 和 JRE 有什么区别?

JDK:Java Development Kit 的简称,Java 开发工具包,提供了 Java
的开发环境和运行环境。

JRE:Java Runtime Environment 的简称,Java 运行环境,为 Java
的运行提供了所需环境。

具体来说 JDK 其实包含了 JRE,同时还包含了编译 Java 源码的编译器 Javac,还包含了很多 Java 程序调试和分析的工具。简单来说:如果你需要运行 Java 程序,只需安装 JRE 就可以了,如果你需要编写 Java 程序,需要安装 JDK。

2. == 和 equals 的区别是什么?

== 解读

对于基本类型和引用类型 == 的作用效果是不同的,如下所示:

基本类型:比较的是值是否相同;

引用类型:比较的是引用是否相同;

代码示例:

class test01
{
    public static void main(String[] args)
    {

        String x = "string";

        String y = "string";

        String z = new String("string");

        System.out.println(x==y); /// true/

        System.out.println(x==z); /// false/

        System.out.println(x.equals(y)); /// true/

        System.out.println(x.equals(z)); /// true/

    }
}

代码解读:因为 x 和 y 指向的是同一个引用,所以 == 也是 true,而 new String()方法则重写开辟了内存空间,所以 == 结果为 false,而 equals 比较的一直是值,所以结果都为 true。

equals 解读

equals 本质上就是 ==,只不过 String 和 Integer 等重写了 equals 方法,把它变成了值比较。看下面的代码就明白了。

首先来看默认情况下 equals 比较一个有相同值的对象,代码如下:


class   Cat  {

    public   Cat (String name) {

        this .name = name;

    }

    private  String name;

    public  String  getName () {

        return  name;

    }

    public   void   setName (String name) {

        this .name = name;

    }

}

Cat c1 =  new  Cat("王磊");

Cat c2 =  new  Cat("王磊");

System.out.println(c1.equals(c2)); /// false/

//  输出结果出乎我们的意料,竟然是 false?这是怎么回事,看了 equals
//  源码就知道了,源码如下:

    public   boolean   equals (Object obj) {

    return  ( this  == obj);

}

//    原来 equals 本质上就是 ==。

//    那问题来了,两个相同值的 String 对象,为什么返回的是 true?代码如下:

String s1 =  new  String("老王");

String s2 =  new  String("老王");

System.out.println(s1.equals(s2)); /// true/

// 同样的,当我们进入 String 的 equals 方法,找到了答案,代码如下:

public   boolean   equals (Object anObject) {
    if  ( this  == anObject) {
        return   true ;
    }
    if  (anObject  instanceof  String) {
        String anotherString = (String)anObject;
        int  n = value.length;
        if  (n == anotherString.value.length) {
            char  v1[] = value;
            char  v2[] = anotherString.value;
            int  i = 0;
            while  (n-- != 0) {
                if  (v1[i] != v2[i])
                    return   false ;
                i++;
            }
            return   true ;
        }
    }
    return   false ;
}

原来是 String 重写了 Object 的 equals 方法,把引用比较改成了值比较。

*总结* :== 对于基本类型来说是值比较,对于引用类型来说是比较的是引用;而 equals 默认情况下是引用比较,只是很多类重新了 equals 方法,比如 String、Integer 等把它变成了值比较,所以一般情况下 equals 比较的是值是否相等。

3. 两个对象的 hashCode() 相同,则 equals() 也一定为 true,对吗?

不对,两个对象的 hashCode() 相同,equals() 不一定 true。

代码示例:


String str1 = "通话";

String str2 = "重地";

System. out. println(String. format("str1:%d | str2:%d", str1.
                                    hashCode(),str2. hashCode()));

System. out. println(str1. equals(str2));

执行的结果:

str1:1179395 | str2:1179395

false

代码解读:很显然"通话"和"重地"的 hashCode() 相同,然而 equals() 则为 false,因为在散列表中,hashCode() 相等即两个键值对的哈希值相等,然而哈希值相等,并不一定能得出键值对相等。

4. final 在 Java 中有什么作用?

  • final 修饰的类叫最终类,该类不能被继承。

  • final 修饰的方法不能被重写。

  • final 修饰的变量叫常量,常量必须初始化,初始化之后值就不能被修改。

5. Java 中的 Math. round(-1. 5) 等于多少?

等于 -1,因为在数轴上取值时,中间值(0.5)向右取整,所以正 0.5 是往上取整,负 0.5 是直接舍弃。

6. String 属于基础的数据类型吗?

String 不属于基础类型,基础类型有 8 种:byte、boolean、char、short、int、float、long、double,而 String 属于对象。

7. Java 中操作字符串都有哪些类?它们之间有什么区别?

操作字符串的类有:String、StringBuffer、StringBuilder。

String 和 StringBuffer、StringBuilder 的区别在于 String 声明的是不可变的对象,每次操作都会生成新的 String 对象,然后将指针指向新的 String 对象,而 StringBuffer、StringBuilder 可以在原有对象的基础上进行操作,所以在经常改变字符串内容的情况下最好不要使用 String。

StringBuffer 和 StringBuilder 最大的区别在于,StringBuffer 是线程安全的,而 StringBuilder 是非线程安全的,但 StringBuilder 的性能却高于 StringBuffer,所以在单线程环境下推荐使用 StringBuilder,多线程环境下推荐使用 StringBuffer。

8. String str="i"与 String str=new String("i")一样吗?

不一样,因为内存的分配方式不一样。String str="i"的方式,Java 虚拟机会将其分配到常量池中;而 String str=new String("i") 则会被分到堆内存中。

9. 如何将字符串反转?

使用 StringBuilder 或者 stringBuffer 的 reverse() 方法。

示例代码:


/// StringBuffer reverse/

StringBuffer stringBuffer = * new*  StringBuffer();

stringBuffer. append("abcdefg");

System. out. println(stringBuffer. reverse()); /// gfedcba/

/// StringBuilder reverse/

StringBuilder stringBuilder = * new*  StringBuilder();

stringBuilder. append("abcdefg");

System. out. println(stringBuilder. reverse()); /// gfedcba/

10. String 类的常用方法都有那些?

  • indexOf():返回指定字符的索引。

  • charAt():返回指定索引处的字符。

  • replace():字符串替换。

  • trim():去除字符串两端空白。

  • split():分割字符串,返回一个分割后的字符串数组。

  • getBytes():返回字符串的 byte 类型数组。

  • length():返回字符串长度。

  • toLowerCase():将字符串转成小写字母。

  • toUpperCase():将字符串转成大写字符。

  • substring():截取字符串。

  • equals():字符串比较。

11. 抽象类必须要有抽象方法吗?

不需要,抽象类不一定非要有抽象方法。

示例代码:

abstract     class     Cat   {

    public     static     void     sayHi  () {

        System. out. println("hi~");

    }

}

上面代码,抽象类并没有抽象方法但完全可以正常运行。

12. 普通类和抽象类有哪些区别?

  • 普通类不能包含抽象方法,抽象类可以包含抽象方法。

  • 抽象类不能直接实例化,普通类可以直接实例化。

13. 抽象类能使用 final 修饰吗?

不能,定义抽象类就是让其他类继承的,如果定义为 final 该类就不能被继承,这样彼此就会产生矛盾,所以 final 不能修饰抽象类,如下图所示,编辑器也会提示错误信息:

14. 接口和抽象类有什么区别?

  • 实现:抽象类的子类使用 extends 来继承;接口必须使用 implements 来实现接口。

  • 构造函数:抽象类可以有构造函数;接口不能有。

  • 实现数量:类可以实现很多个接口;但是只能继承一个抽象类。

  • 访问修饰符:接口中的方法默认使用 public 修饰;抽象类中的方法可以是任意访问修饰符。

15. Java 中 IO 流分为几种?

按功能来分:输入流(input)、输出流(output)。

按类型来分:字节流和字符流。

字节流和字符流的区别是:字节流按 8位传输以字节为单位输入输出数据,

字符流按 16位传输以字符为单位输入输出数据。

16. BIO、NIO、AIO 有什么区别?

  • BIO:Block IO 同步阻塞式 IO,就是我们平常使用的传统 IO,它的特点是模式简单使用方便,并发处理能力低。

  • NIO:Non IO 同步非阻塞 IO,是传统 IO 的升级,客户端和服务器端通过 Channel(通道)通讯,实现了多路复用。

  • AIO:Asynchronous IO 是 NIO 的升级,也叫 NIO2,实现了异步非堵塞 IO ,异步 IO 的操作基于事件和回调机制。

17. Files的常用方法都有哪些?

  • Files. exists():检测文件路径是否存在。

  • Files. createFile():创建文件。

  • Files. createDirectory():创建文件夹。

  • Files. delete():删除一个文件或目录。

  • Files. copy():复制文件。

  • Files. move():移动文件。

  • Files. size():查看文件个数。

  • Files. read():读取文件。

  • Files. write():写入文件。

容器

18. Java 容器都有哪些?

Java 容器分为 Collection 和 Map 两大类,其下又有很多子类,如下所示:

  • Collection

  • List

    • ArrayList

    • LinkedList

    • Vector

    • Stack

  • Set

    • HashSet

    • LinkedHashSet

    • TreeSet

  • Map

  • HashMap

    • LinkedHashMap
  • TreeMap

  • ConcurrentHashMap

  • Hashtable

19. Collection 和 Collections 有什么区别?

  • Collection 是一个集合接口,它提供了对集合对象进行基本操作的通用接口方法,所有集合都是它的子类,比如 List、Set 等。

  • Collections 是一个包装类,包含了很多静态方法,不能被实例化,就像一个工具类,比如提供的排序方法: Collections. sort(list)。

20. List、Set、Map 之间的区别是什么?

List、Set、Map 的区别主要体现在两个方面:元素是否有序、是否允许元素重复。

三者之间的区别,如下表:

21. HashMap 和 Hashtable 有什么区别?

  • 存储:HashMap 运行 key 和 value 为 null,而 Hashtable 不允许。

  • 线程安全:Hashtable 是线程安全的,而 HashMap 是非线程安全的。

  • 推荐使用:在 Hashtable 的类注释可以看到,Hashtable 是保留类不建议使用,推荐在单线程环境下使用 HashMap 替代,如果需要多线程使用则用 ConcurrentHashMap 替代。

22. 如何决定使用 HashMap 还是 TreeMap?

对于在 Map 中插入、删除、定位一个元素这类操作,HashMap 是最好的选择,因为相对而言 HashMap 的插入会更快,但如果你要对一个 key 集合进行有序的遍历,那 TreeMap 是更好的选择。

23. 说一下 HashMap 的实现原理?

HashMap 基于 Hash 算法实现的,我们通过 put(key,value)存储,get(key)来获取。当传入 key 时,HashMap 会根据 key. hashCode() 计算出 hash 值,根据 hash 值将 value 保存在 bucket 里。当计算出的 hash 值相同时,我们称之为 hash 冲突,HashMap 的做法是用链表和红黑树存储相同 hash 值的 value。当 hash 冲突的个数比较少时,使用链表否则使用红黑树。

24. 说一下 HashSet 的实现原理?

HashSet 是基于 HashMap 实现的,HashSet 底层使用 HashMap 来保存所有元素,因此 HashSet 的实现比较简单,相关 HashSet 的操作,基本上都是直接调用底层 HashMap 的相关方法来完成,HashSet 不允许重复的值。

25. ArrayList 和 LinkedList 的区别是什么?

  • 数据结构实现:ArrayList 是动态数组的数据结构实现,而 LinkedList 是双向链表的数据结构实现。

  • 随机访问效率:ArrayList 比 LinkedList 在随机访问的时候效率要高,因为 LinkedList 是线性的数据存储方式,所以需要移动指针从前往后依次查找。

  • 增加和删除效率:在非首尾的增加和删除操作,LinkedList 要比 ArrayList 效率要高,因为 ArrayList 增删操作要影响数组内的其他数据的下标。

综合来说,在需要频繁读取集合中的元素时,更推荐使用 ArrayList,而在插入和删除操作较多时,更推荐使用 LinkedList。

  1. 如何实现数组和 List 之间的转换?
  • 数组转 List:使用 Arrays. asList(array) 进行转换。

  • List 转数组:使用 List 自带的 toArray() 方法。

代码示例:

/ list to array/

List<String> list = * new* ArrayList<String>();

list. add("王磊");

list. add("的博客");

list. toArray();

/ array to list/

String[] array = * new* String[]{"王磊","的博客"};

Arrays. asList(array);

27. ArrayList 和 Vector 的区别是什么?

  • 线程安全:Vector 使用了 Synchronized 来实现线程同步,是线程安全的,而 ArrayList 是非线程安全的。

  • 性能:ArrayList 在性能方面要优于 Vector。

  • 扩容:ArrayList 和 Vector 都会根据实际的需要动态的调整容量,只不过在 Vector 扩容每次会增加 1 倍,而 ArrayList 只会增加 50%。

28. Array 和 ArrayList 有何区别?

  • Array 可以存储基本数据类型和对象,ArrayList 只能存储对象。

  • Array 是指定固定大小的,而 ArrayList 大小是自动扩展的。

  • Array 内置方法没有 ArrayList 多,比如 addAll、removeAll、iteration 等方法只有 ArrayList 有。

29. 在 Queue 中 poll()和 remove()有什么区别?

  • 相同点:都是返回第一个元素,并在队列中删除返回的对象。

  • 不同点:如果没有元素 poll()会返回 null,而 remove()会直接抛出 NoSuchElementException 异常。

代码示例:

Queue<String> queue = * new* LinkedList<String>();

queue. offer("string"); / add/

System. out. println(queue. poll());

System. out. println(queue. remove());

System. out. println(queue. size());

30. 哪些集合类是线程安全的?

Vector、Hashtable、Stack 都是线程安全的,而像 HashMap 则是非线程安全的,不过在 JDK 1.5 之后随着 Java. util. concurrent 并发包的出现,它们也有了自己对应的线程安全类,比如 HashMap 对应的线程安全类就是 ConcurrentHashMap。

31. 迭代器 Iterator 是什么?

Iterator 接口提供遍历任何 Collection 的接口。我们可以从一个 Collection 中使用迭代器方法来获取迭代器实例。迭代器取代了 Java 集合框架中的 Enumeration,迭代器允许调用者在迭代过程中移除元素。

32. Iterator 怎么使用?有什么特点?

Iterator 使用代码如下:

List<String> list = * new* ArrayList<>();

Iterator<String> it = list. iterator();

while* (it. hasNext()){

String obj = it. next();

System. out. println(obj);

}

Iterator 的特点是更加安全,因为它可以确保,在当前遍历的集合元素被更改的时候,就会抛出 ConcurrentModificationException 异常。

33. Iterator 和 ListIterator 有什么区别?

  • Iterator 可以遍历 Set 和 List 集合,而 ListIterator 只能遍历 List。

  • Iterator 只能单向遍历,而 ListIterator 可以双向遍历(向前/后遍历)。

  • ListIterator 从 Iterator 接口继承,然后添加了一些额外的功能,比如添加一个元素、替换一个元素、获取前面或后面元素的索引位置。

34. 怎么确保一个集合不能被修改?

可以使用 Collections. unmodifiableCollection(Collection c) 方法来创建一个只读集合,这样改变集合的任何操作都会抛出 Java. lang. UnsupportedOperationException 异常。

示例代码如下:

List<String> list = * new* ArrayList<>();

list. add("x");

Collection<String> clist = Collections. unmodifiableCollection(list);

clist. add("y"); / 运行时此行报错/

System. out. println(list. size());

多线程

35. 并行和并发有什么区别?

  • 并行:多个处理器或多核处理器同时处理多个任务。

  • 并发:多个任务在同一个 CPU 核上,按细分的时间片轮流(交替)执行,从逻辑上来看那些任务是同时执行。

如下图:

并发 = 两个队列和一台咖啡机。

并行 = 两个队列和两台咖啡机。

36. 线程和进程的区别?

一个程序下至少有一个进程,一个进程下至少有一个线程,一个进程下也可以有多个线程来增加程序的执行速度。

  1. 守护线程是什么?

守护线程是运行在后台的一种特殊进程。它独立于控制终端并且周期性地执行某种任务或等待处理某些发生的事件。在 Java 中垃圾回收线程就是特殊的守护线程。

38. 创建线程有哪几种方式?

创建线程有三种方式:

  • 继承 Thread 重写 run 方法;

  • 实现 Runnable 接口;

  • 实现 Callable 接口。

39. 说一下 runnable 和 callable 有什么区别?

runnable 没有返回值,callable 可以拿到有返回值,callable 可以看作是 runnable 的补充。

40. 线程有哪些状态?

线程的状态:

  • NEW 尚未启动

  • RUNNABLE 正在执行中

  • BLOCKED 阻塞的(被同步锁或者IO锁阻塞)

  • WAITING 永久等待状态

  • TIMED_WAITING 等待指定的时间重新被唤醒的状态

  • TERMINATED 执行完成

41. sleep() 和 wait() 有什么区别?

  • 类的不同:sleep() 来自 Thread,wait() 来自 Object。

  • 释放锁:sleep() 不释放锁;wait() 释放锁。

  • 用法不同:sleep() 时间到会自动恢复;wait() 可以使用 notify()/notifyAll()直接唤醒。

42. notify()和 notifyAll()有什么区别?

notifyAll()会唤醒所有的线程,notify()之后唤醒一个线程。notifyAll() 调用后,会将全部线程由等待池移到锁池,然后参与锁的竞争,竞争成功则继续执行,如果不成功则留在锁池等待锁被释放后再次参与竞争。而 notify()只会唤醒一个线程,具体唤醒哪一个线程由虚拟机控制。

43. 线程的 run() 和 start() 有什么区别?

start() 方法用于启动线程,run() 方法用于执行线程的运行时代码。run() 可以重复调用,而 start() 只能调用一次。

44. 创建线程池有哪几种方式?

线程池创建有七种方式,最核心的是最后一种:

  • newSingleThreadExecutor():它的特点在于工作线程数目被限制为 1,操作一个无界的工作队列,所以它保证了所有任务的都是被顺序执行,最多会有一个任务处于活动状态,并且不允许使用者改动线程池实例,因此可以避免其改变线程数目;

  • newCachedThreadPool():它是一种用来处理大量短时间工作任务的线程池,具有几个鲜明特点:它会试图缓存线程并重用,当无缓存线程可用时,就会创建新的工作线程;如果线程闲置的时间超过 60 秒,则被终止并移出缓存;长时间闲置时,这种线程池,不会消耗什么资源。其内部使用 SynchronousQueue 作为工作队列;

  • newFixedThreadPool(int nThreads):重用指定数目(nThreads)的线程,其背后使用的是无界的工作队列,任何时候最多有 nThreads 个工作线程是活动的。这意味着,如果任务数量超过了活动队列数目,将在工作队列中等待空闲线程出现;如果有工作线程退出,将会有新的工作线程被创建,以补足指定的数目 nThreads;

  • newSingleThreadScheduledExecutor():创建单线程池,返回 ScheduledExecutorService,可以进行定时或周期性的工作调度;

  • newScheduledThreadPool(int corePoolSize):和newSingleThreadScheduledExecutor()类似,创建的是个 ScheduledExecutorService,可以进行定时或周期性的工作调度,区别在于单一工作线程还是多个工作线程;

  • newWorkStealingPool(int parallelism):这是一个经常被人忽略的线程池,Java 8 才加入这个创建方法,其内部会构建ForkJoinPool,利用Work-Stealing算法,并行地处理任务,不保证处理顺序;

  • ThreadPoolExecutor():是最原始的线程池创建,上面1-3创建方式都是对ThreadPoolExecutor的封装。

45. 线程池都有哪些状态?

  • RUNNING:这是最正常的状态,接受新的任务,处理等待队列中的任务。

  • SHUTDOWN:不接受新的任务提交,但是会继续处理等待队列中的任务。

  • STOP:不接受新的任务提交,不再处理等待队列中的任务,中断正在执行任务的线程。

  • TIDYING:所有的任务都销毁了,workCount 为 0,线程池的状态在转换为 TIDYING 状态时,会执行钩子方法 terminated()。

  • TERMINATED:terminated()方法结束后,线程池的状态就会变成这个。

46. 线程池中 submit() 和 execute() 方法有什么区别?

  • execute():只能执行 Runnable 类型的任务。

  • submit():可以执行 Runnable 和 Callable 类型的任务。

Callable 类型的任务可以获取执行的返回值,而 Runnable 执行无返回值。

47. 在 Java 程序中怎么保证多线程的运行安全?

  • 方法一:使用安全类,比如 Java. util. concurrent 下的类。

  • 方法二:使用自动锁 synchronized。

  • 方法三:使用手动锁 Lock。

手动锁 Java 示例代码如下:

Lock lock = * new* ReentrantLock();

lock. lock();

try {

System. out. println("获得锁");

} * catch* (Exception e) {

/ TODO: handle exception/

} * finally* {

System. out. println("释放锁");

lock. unlock();

}

48. 多线程中 synchronized 锁升级的原理是什么?

synchronized 锁升级原理:在锁对象的对象头里面有一个 threadid 字段,在第一次访问的时候 threadid 为空,jvm 让其持有偏向锁,并将 threadid 设置为其线程 id,再次进入的时候会先判断 threadid 是否与其线程 id 一致,如果一致则可以直接使用此对象,如果不一致,则升级偏向锁为轻量级锁,通过自旋循环一定次数来获取锁,执行一定次数之后,如果还没有正常获取到要使用的对象,此时就会把锁从轻量级升级为重量级锁,此过程就构成了 synchronized 锁的升级。

锁的升级的目的:锁升级是为了减低了锁带来的性能消耗。在 Java 6 之后优化 synchronized 的实现方式,使用了偏向锁升级为轻量级锁再升级到重量级锁的方式,从而减低了锁带来的性能消耗。

49. 什么是死锁?

当线程 A 持有独占锁a,并尝试去获取独占锁 b 的同时,线程 B 持有独占锁 b,并尝试获取独占锁 a 的情况下,就会发生 AB 两个线程由于互相持有对方需要的锁,而发生的阻塞现象,我们称为死锁。

50. 怎么防止死锁?

  • 尽量使用 tryLock(long timeout, TimeUnit unit)的方法(ReentrantLock、ReentrantReadWriteLock),设置超时时间,超时可以退出防止死锁。

  • 尽量使用 Java. util. concurrent 并发类代替自己手写锁。

  • 尽量降低锁的使用粒度,尽量不要几个功能用同一把锁。

  • 尽量减少同步的代码块。

51. ThreadLocal 是什么?有哪些使用场景?

ThreadLocal 为每个使用该变量的线程提供独立的变量副本,所以每一个线程都可以独立地改变自己的副本,而不会影响其它线程所对应的副本。

ThreadLocal 的经典使用场景是数据库连接和 session 管理等。

52. 说一下 synchronized 底层实现原理?

synchronized 是由一对 monitorenter/monitorexit 指令实现的,monitor 对象是同步的基本实现单元。在 Java 6 之前,monitor 的实现完全是依靠操作系统内部的互斥锁,因为需要进行用户态到内核态的切换,所以同步操作是一个无差别的重量级操作,性能也很低。但在 Java 6 的时候,Java 虚拟机 对此进行了大刀阔斧地改进,提供了三种不同的 monitor 实现,也就是常说的三种不同的锁:偏向锁(Biased Locking)、轻量级锁和重量级锁,大大改进了其性能。

53. synchronized 和 volatile 的区别是什么?

  • volatile 是变量修饰符;synchronized 是修饰类、方法、代码段。

  • volatile 仅能实现变量的修改可见性,不能保证原子性;而 synchronized 则可以保证变量的修改可见性和原子性。

  • volatile 不会造成线程的阻塞;synchronized 可能会造成线程的阻塞。

54. synchronized 和 Lock 有什么区别?

  • synchronized 可以给类、方法、代码块加锁;而 lock 只能给代码块加锁。

  • synchronized 不需要手动获取锁和释放锁,使用简单,发生异常会自动释放锁,不会造成死锁;而 lock 需要自己加锁和释放锁,如果使用不当没有 unLock()去释放锁就会造成死锁。

  • 通过 Lock 可以知道有没有成功获取锁,而 synchronized 却无法办到。

55. synchronized 和 ReentrantLock 区别是什么?

synchronized 早期的实现比较低效,对比 ReentrantLock,大多数场景性能都相差较大,但是在 Java 6 中对 synchronized 进行了非常多的改进。

主要区别如下:

  • ReentrantLock 使用起来比较灵活,但是必须有释放锁的配合动作;

  • ReentrantLock 必须手动获取与释放锁,而 synchronized 不需要手动释放和开启锁;

  • ReentrantLock 只适用于代码块锁,而 synchronized 可用于修饰方法、代码块等。

56. 说一下 atomic 的原理?

atomic 主要利用 CAS (Compare And Wwap) 和 volatile 和 native 方法来保证原子操作,从而避免 synchronized 的高开销,执行效率大为提升。

反射

57. 什么是反射?

反射是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意一个方法和属性;这种动态获取的信息以及动态调用对象的方法的功能称为 Java 语言的反射机制。

58. 什么是 Java 序列化?什么情况下需要序列化?

Java 序列化是为了保存各种对象在内存中的状态,并且可以把保存的对象状态再读出来。

以下情况需要使用 Java 序列化:

  • 想把的内存中的对象状态保存到一个文件中或者数据库中时候;

  • 想用套接字在网络上传送对象的时候;

  • 想通过RMI(远程方法调用)传输对象的时候。

59. 动态代理是什么?有哪些应用?

动态代理是运行时动态生成代理类。

动态代理的应用有 spring aop、hibernate 数据查询、测试框架的后端 mock、rpc,Java注解对象获取等。

60. 怎么实现动态代理?

JDK 原生动态代理和 cglib 动态代理。JDK 原生动态代理是基于接口实现的,而 cglib 是基于继承当前类的子类实现的。

对象拷贝

61. 为什么要使用克隆?

克隆的对象可能包含一些已经修改过的属性,而 new 出来的对象的属性都还是初始化时候的值,所以当需要一个新的对象来保存当前对象的"状态"就靠克隆方法了。

62. 如何实现对象克隆?

  • 实现 Cloneable 接口并重写 Object 类中的 clone() 方法。

  • 实现 Serializable 接口,通过对象的序列化和反序列化实现克隆,可以实现真正的深度克隆。

63. 深拷贝和浅拷贝区别是什么?

  • 浅克隆:当对象被复制时只复制它本身和其中包含的值类型的成员变量,而引用类型的成员对象并没有复制。

  • 深克隆:除了对象本身被复制外,对象所包含的所有成员变量也将复制。

Java Web

64. JSP 和 servlet 有什么区别?

JSP 是 servlet 技术的扩展,本质上就是 servlet 的简易方式。servlet 和 JSP 最主要的不同点在于,servlet 的应用逻辑是在 Java 文件中,并且完全从表示层中的 html 里分离开来,而 JSP 的情况是 Java 和 html 可以组合成一个扩展名为 JSP 的文件。JSP 侧重于视图,servlet 主要用于控制逻辑。

65. JSP 有哪些内置对象?作用分别是什么?

JSP 有 9 大内置对象:

  • request:封装客户端的请求,其中包含来自 get 或 post 请求的参数;

  • response:封装服务器对客户端的响应;

  • pageContext:通过该对象可以获取其他对象;

  • session:封装用户会话的对象;

  • application:封装服务器运行环境的对象;

  • out:输出服务器响应的输出流对象;

  • config:Web 应用的配置对象;

  • page:JSP 页面本身(相当于 Java 程序中的 this);

  • exception:封装页面抛出异常的对象。

66. 说一下 JSP 的 4 种作用域?

  • page:代表与一个页面相关的对象和属性。

  • request:代表与客户端发出的一个请求相关的对象和属性。一个请求可能跨越多个页面,涉及多个 Web 组件;需要在页面显示的临时数据可以置于此作用域。

  • session:代表与某个用户与服务器建立的一次会话相关的对象和属性。跟某个用户相关的数据应该放在用户自己的 session 中。

  • application:代表与整个 Web 应用程序相关的对象和属性,它实质上是跨越整个 Web 应用程序,包括多个页面、请求和会话的一个全局作用域。

  • 存储位置不同:session 存储在服务器端;cookie 存储在浏览器端。

  • 安全性不同:cookie 安全性一般,在浏览器存储,可以被伪造和修改。

  • 容量和个数限制:cookie 有容量限制,每个站点下的 cookie 也有个数限制。

  • 存储的多样性:session 可以存储在 Redis 中、数据库中、应用程序中;而 cookie 只能存储在浏览器中。

68. 说一下 session 的工作原理?

session 的工作原理是客户端登录完成之后,服务器会创建对应的 session,session 创建完之后,会把 session 的 id 发送给客户端,客户端再存储到浏览器中。这样客户端每次访问服务器时,都会带着 sessionid,服务器拿到 sessionid 之后,在内存找到与之对应的 session 这样就可以正常工作了。

可以用,session 只是依赖 cookie 存储 sessionid,如果 cookie 被禁用了,可以使用 url 中添加 sessionid 的方式保证 session 能正常使用。

70. spring mvc 和 struts 的区别是什么?

  • 拦截级别:struts2 是类级别的拦截;spring mvc 是方法级别的拦截。

  • 数据独立性:spring mvc 的方法之间基本上独立的,独享 request 和 response 数据,请求数据通过参数获取,处理结果通过 ModelMap 交回给框架,方法之间不共享变量;而 struts2 虽然方法之间也是独立的,但其所有 action 变量是共享的,这不会影响程序运行,却给我们编码和读程序时带来了一定的麻烦。

  • 拦截机制:struts2 有以自己的 interceptor 机制,spring mvc 用的是独立的 aop 方式,这样导致struts2 的配置文件量比 spring mvc 大。

  • 对 ajax 的支持:spring mvc 集成了ajax,所有 ajax 使用很方便,只需要一个注解 @ResponseBody 就可以实现了;而 struts2 一般需要安装插件或者自己写代码才行。

71. 如何避免 SQL 注入?

  • 使用预处理 PreparedStatement。

  • 使用正则表达式过滤掉字符中的特殊字符。

72. 什么是 XSS 攻击,如何避免?

XSS 攻击:即跨站脚本攻击,它是 Web 程序中常见的漏洞。原理是攻击者往 Web 页面里插入恶意的脚本代码(css 代码、Javascript 代码等),当用户浏览该页面时,嵌入其中的脚本代码会被执行,从而达到恶意攻击用户的目的,如盗取用户 cookie、破坏页面结构、重定向到其他网站等。

预防 XSS 的核心是必须对输入的数据做过滤处理。

73. 什么是 CSRF 攻击,如何避免?

CSRF:Cross-Site Request Forgery(中文:跨站请求伪造),可以理解为攻击者盗用了你的身份,以你的名义发送恶意请求,比如:以你名义发送邮件、发消息、购买商品,虚拟货币转账等。

防御手段:

  • 验证请求来源地址;

  • 关键操作添加验证码;

  • 在请求地址添加 token 并验证。

异常

74. throw 和 throws 的区别?

  • throw:是真实抛出一个异常。

  • throws:是声明可能会抛出一个异常。

75. final、finally、finalize 有什么区别?

  • final:是修饰符,如果修饰类,此类不能被继承;如果修饰方法和变量,则表示此方法和此变量不能在被改变,只能使用。

  • finally:是 try{} catch{} finally{} 最后一部分,表示不论发生任何情况都会执行,finally 部分可以省略,但如果 finally 部分存在,则一定会执行 finally 里面的代码。

  • finalize: 是 Object 类的一个方法,在垃圾收集器执行的时候会调用被回收对象的此方法。

76. try-catch-finally 中哪个部分可以省略?

try-catch-finally 其中 catch 和 finally 都可以被省略,但是不能同时省略,也就是说有 try 的时候,必须后面跟一个 catch 或者 finally。

77. try-catch-finally 中,如果 catch 中 return 了,finally 还会执行吗?

finally 一定会执行,即使是 catch 中 return 了,catch 中的 return 会等 finally 中的代码执行完之后,才会执行。

78. 常见的异常类有哪些?

  • NullPointerException 空指针异常

  • ClassNotFoundException 指定类不存在

  • NumberFormatException 字符串转换为数字异常

  • IndexOutOfBoundsException 数组下标越界异常

  • ClassCastException 数据类型转换异常

  • FileNotFoundException 文件未找到异常

  • NoSuchMethodException 方法不存在异常

  • IOException IO 异常

  • SocketException Socket 异常

网络

79. http 响应码 301 和 302 代表的是什么?有什么区别?

301:永久重定向。

302:暂时重定向。

它们的区别是,301 对搜索引擎优化(SEO)更加有利;302 有被提示为网络拦截的风险。

80. forward 和 redirect 的区别?

forward 是转发 和 redirect 是重定向:

  • 地址栏 url 显示:foward url 不会发生改变,redirect url 会发生改变;

  • 数据共享:forward 可以共享 request 里的数据,redirect 不能共享;

  • 效率:forward 比 redirect 效率高。

81. 简述 tcp 和 udp的区别?

tcp 和 udp 是 OSI 模型中的运输层中的协议。tcp 提供可靠的通信传输,而 udp 则常被用于让广播和细节控制交给应用的通信传输。

两者的区别大致如下:

  • tcp 面向连接,udp 面向非连接即发送数据前不需要建立链接;

  • tcp 提供可靠的服务(数据传输),udp 无法保证;

  • tcp 面向字节流,udp 面向报文;

  • tcp 数据传输慢,udp 数据传输快;

82. tcp 为什么要三次握手,两次不行吗?为什么?

如果采用两次握手,那么只要服务器发出确认数据包就会建立连接,但由于客户端此时并未响应服务器端的请求,那此时服务器端就会一直在等待客户端,这样服务器端就白白浪费了一定的资源。若采用三次握手,服务器端没有收到来自客户端的再此确认,则就会知道客户端并没有要求建立请求,就不会浪费服务器的资源。

83. 说一下 tcp 粘包是怎么产生的?

tcp 粘包可能发生在发送端或者接收端,分别来看两端各种产生粘包的原因:

  • 发送端粘包:发送端需要等缓冲区满才发送出去,造成粘包;

  • 接收方粘包:接收方不及时接收缓冲区的包,造成多个包接收。

84. OSI 的七层模型都有哪些?

  • 物理层:利用传输介质为数据链路层提供物理连接,实现比特流的透明传输。

  • 数据链路层:负责建立和管理节点间的链路。

  • 网络层:通过路由选择算法,为报文或分组通过通信子网选择最适当的路径。

  • 传输层:向用户提供可靠的端到端的差错和流量控制,保证报文的正确传输。

  • 会话层:向两个实体的表示层提供建立和使用连接的方法。

  • 表示层:处理用户信息的表示问题,如编码、数据格式转换和加密解密等。

  • 应用层:直接向用户提供服务,完成用户希望在网络上完成的各种工作。

85. get 和 post 请求有哪些区别?

  • get 请求会被浏览器主动缓存,而 post 不会。

  • get 传递参数有大小限制,而 post 没有。

  • post 参数传输更安全,get 的参数会明文限制在 url 上,post 不会。

86. 如何实现跨域?

实现跨域有以下几种方案:

  • 服务器端运行跨域 设置 CORS 等于 *;

  • 在单个接口使用注解 @CrossOrigin 运行跨域;

  • 使用 jsonp 跨域;

87. 说一下 JSONP 实现原理?

jsonp:JSON with Padding,它是利用script标签的 src 连接可以访问不同源的特性,加载远程返回的"JS 函数"来执行的。

设计模式

88. 说一下你熟悉的设计模式?

  • 单例模式:保证被创建一次,节省系统开销。

  • 工厂模式(简单工厂、抽象工厂):解耦代码。

  • 观察者模式:定义了对象之间的一对多的依赖,这样一来,当一个对象改变时,它的所有的依赖者都会收到通知并自动更新。

  • 外观模式:提供一个统一的接口,用来访问子系统中的一群接口,外观定义了一个高层的接口,让子系统更容易使用。

  • 模版方法模式:定义了一个算法的骨架,而将一些步骤延迟到子类中,模版方法使得子类可以在不改变算法结构的情况下,重新定义算法的步骤。

  • 状态模式:允许对象在内部状态改变时改变它的行为,对象看起来好像修改了它的类。

89. 简单工厂和抽象工厂有什么区别?

  • 简单工厂:用来生产同一等级结构中的任意产品,对于增加新的产品,无能为力。

  • 工厂方法:用来生产同一等级结构中的固定产品,支持增加任意产品。

  • 抽象工厂:用来生产不同产品族的全部产品,对于增加新的产品,无能为力;支持增加产品族。

Spring/Spring MVC

90. 为什么要使用 spring?

  • spring 提供 ioc 技术,容器会帮你管理依赖的对象,从而不需要自己创建和管理依赖对象了,更轻松的实现了程序的解耦。

  • spring 提供了事务支持,使得事务操作变的更加方便。

  • spring 提供了面向切片编程,这样可以更方便的处理某一类的问题。

  • 更方便的框架集成,spring 可以很方便的集成其他框架,比如 MyBatis、hibernate 等。

91. 解释一下什么是 aop?

aop 是面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。

简单来说就是统一处理某一"切面"(类)的问题的编程思想,比如统一处理日志、异常等。

92. 解释一下什么是 ioc?

ioc:Inversionof Control(中文:控制反转)是 spring 的核心,对于 spring 框架来说,就是由 spring 来负责控制对象的生命周期和对象间的关系。

简单来说,控制指的是当前对象对内部成员的控制权;控制反转指的是,这种控制权不由当前对象管理了,由其他(类,第三方容器)来管理。

93. spring 有哪些主要模块?

  • spring core:框架的最基础部分,提供 ioc 和依赖注入特性。

  • spring context:构建于 core 封装包基础上的 context 封装包,提供了一种框架式的对象访问方法。

  • spring dao:Data Access Object 提供了JDBC的抽象层。

  • spring aop:提供了面向切面的编程实现,让你可以自定义拦截器、切点等。

  • spring Web:提供了针对 Web 开发的集成特性,例如文件上传,利用 servlet listeners 进行 ioc 容器初始化和针对 Web 的 ApplicationContext。

  • spring Web mvc:spring 中的 mvc 封装包提供了 Web 应用的 Model-View-Controller(MVC)的实现。

94. spring 常用的注入方式有哪些?

  • setter 属性注入

  • 构造方法注入

  • 注解方式注入

95. spring 中的 bean 是线程安全的吗?

spring 中的 bean 默认是单例模式,spring 框架并没有对单例 bean 进行多线程的封装处理。

实际上大部分时候 spring bean 无状态的(比如 dao 类),所有某种程度上来说 bean 也是安全的,但如果 bean 有状态的话(比如 view model 对象),那就要开发者自己去保证线程安全了,最简单的就是改变 bean 的作用域,把"singleton"变更为"prototype",这样请求 bean 相当于 new Bean()了,所以就可以保证线程安全了。

  • 有状态就是有数据存储功能。

  • 无状态就是不会保存数据。

96. spring 支持几种 bean 的作用域?

spring 支持 5 种作用域,如下:

  • singleton:spring ioc 容器中只存在一个 bean 实例,bean 以单例模式存在,是系统默认值;

  • prototype:每次从容器调用 bean 时都会创建一个新的示例,既每次 getBean()相当于执行 new Bean()操作;

  • Web 环境下的作用域:

  • request:每次 http 请求都会创建一个 bean;

  • session:同一个 http session 共享一个 bean 实例;

  • global-session:用于 portlet 容器,因为每个 portlet 有单独的 session,globalsession 提供一个全局性的 http session。

*注意:* 使用 prototype 作用域需要慎重的思考,因为频繁创建和销毁 bean 会带来很大的性能开销。

97. spring 自动装配 bean 有哪些方式?

  • no:默认值,表示没有自动装配,应使用显式 bean 引用进行装配。

  • byName:它根据 bean 的名称注入对象依赖项。

  • byType:它根据类型注入对象依赖项。

  • 构造函数:通过构造函数来注入依赖项,需要设置大量的参数。

  • autodetect:容器首先通过构造函数使用 autowire 装配,如果不能,则通过 byType 自动装配。

98. spring 事务实现方式有哪些?

  • 声明式事务:声明式事务也有两种实现方式,基于 xml 配置文件的方式和注解方式(在类上添加 @Transaction 注解)。

  • 编码方式:提供编码的形式管理和维护事务。

99. 说一下 spring 的事务隔离?

spring 有五大隔离级别,默认值为 ISOLATION\DEFAULT(使用数据库的设置),其他四个隔离级别和数据库的隔离级别一致:

ISOLATION\DEFAULT:用底层数据库的设置隔离级别,数据库设置的是什么我就用什么;

ISOLATION/READ/UNCOMMITTED:未提交读,最低隔离级别、事务未提交前,就可被其他事务读取(会出现幻读、脏读、不可重复读);

ISOLATION/READ/COMMITTED:提交读,一个事务提交后才能被其他事务读取到(会造成幻读、不可重复读),SQL server 的默认级别;

ISOLATION/REPEATABLE/READ:可重复读,保证多次读取同一个数据时,其值都和事务开始时候的内容是一致,禁止读取到别的事务未提交的数据(会造成幻读),MySQL 的默认级别;

ISOLATION\SERIALIZABLE:序列化,代价最高最可靠的隔离级别,该隔离级别能防止脏读、不可重复读、幻读。

*脏读* :表示一个事务能够读取另一个事务中还未提交的数据。比如,某个事务尝试插入记录 A,此时该事务还未提交,然后另一个事务尝试读取到了记录 A。

*不可重复读* :是指在一个事务内,多次读同一数据。

*幻读* :指同一个事务内多次查询返回的结果集不一样。比如同一个事务 A 第一次查询时候有 n 条记录,但是第二次同等条件下查询却有 n+1 条记录,这就好像产生了幻觉。发生幻读的原因也是另外一个事务新增或者删除或者修改了第一个事务结果集里面的数据,同一个记录的数据内容被修改了,所有数据行的记录就变多或者变少了。

100. 说一下 spring mvc 运行流程?

  • spring mvc 先将请求发送给 DispatcherServlet。

  • DispatcherServlet 查询一个或多个 HandlerMapping,找到处理请求的 Controller。

  • DispatcherServlet 再把请求提交到对应的 Controller。

  • Controller 进行业务逻辑处理后,会返回一个ModelAndView。

  • Dispathcher 查询一个或多个 ViewResolver 视图解析器,找到 ModelAndView 对象指定的视图对象。

  • 视图对象负责渲染返回给客户端。

101. spring mvc 有哪些组件?

  • 前置控制器 DispatcherServlet。

  • 映射控制器 HandlerMapping。

  • 处理器 Controller。

  • 模型和视图 ModelAndView。

  • 视图解析器 ViewResolver。

102. @RequestMapping 的作用是什么?

将 http 请求映射到相应的类/方法上。

103. @Autowired 的作用是什么?

@Autowired 它可以对类成员变量、方法及构造函数进行标注,完成自动装配的工作,通过@Autowired 的使用来消除 set/get 方法。

Spring Boot/Spring Cloud

104. 什么是 spring boot?

spring boot 是为 spring 服务的,是用来简化新 spring 应用的初始搭建以及开发过程的。

105. 为什么要用 spring boot?

  • 配置简单

  • 独立运行

  • 自动装配

  • 无代码生成和 xml 配置

  • 提供应用监控

  • 易上手

  • 提升开发效率

106. spring boot 核心配置文件是什么?

spring boot 核心的两个配置文件:

  • bootstrap (. yml 或者 . properties):boostrap 由父 ApplicationContext 加载的,比 applicaton 优先加载,且 boostrap 里面的属性不能被覆盖;

  • application (. yml 或者 . properties):用于 spring boot 项目的自动化配置。

107. spring boot 配置文件有哪几种类型?它们有什么区别?

配置文件有 . properties 格式和 . yml 格式,它们主要的区别是书法风格不同。

. properties 配置如下:

spring. RabbitMQ. port=5672

. yml 配置如下:

spring:

RabbitMQ:

port: 5672

. yml 格式不支持 @PropertySource 注解导入。

108. spring boot 有哪些方式可以实现热部署?

  • 使用 devtools 启动热部署,添加 devtools 库,在配置文件中把 spring. devtools. restart. enabled 设置为 true;

  • 使用 Intellij Idea 编辑器,勾上自动编译或手动重新编译。

109. jpa 和 hibernate 有什么区别?

jpa 全称 Java Persistence API,是 Java 持久化接口规范,hibernate 属于 jpa 的具体实现。

110. 什么是 spring cloud?

spring cloud 是一系列框架的有序集合。它利用 spring boot 的开发便利性巧妙地简化了分布式系统基础设施的开发,如服务发现注册、配置中心、消息总线、负载均衡、断路器、数据监控等,都可以用 spring boot 的开发风格做到一键启动和部署。

111. spring cloud 断路器的作用是什么?

在分布式架构中,断路器模式的作用也是类似的,当某个服务单元发生故障(类似用电器发生短路)之后,通过断路器的故障监控(类似熔断保险丝),向调用方返回一个错误响应,而不是长时间的等待。这样就不会使得线程因调用故障服务被长时间占用不释放,避免了故障在分布式系统中的蔓延。

112. spring cloud 的核心组件有哪些?

  • Eureka:服务注册于发现。

  • Feign:基于动态代理机制,根据注解和选择的机器,拼接请求 url 地址,发起请求。

  • Ribbon:实现负载均衡,从一个服务的多台机器中选择一台。

  • Hystrix:提供线程池,不同的服务走不同的线程池,实现了不同服务调用的隔离,避免了服务雪崩的问题。

  • Zuul:网关管理,由 Zuul 网关转发请求给对应的服务。

Hibernate

113. 为什么要使用 hibernate?

  • hibernate 是对 jdbc 的封装,大大简化了数据访问层的繁琐的重复性代码。

  • hibernate 是一个优秀的 ORM 实现,很多程度上简化了 DAO 层的编码功能。

  • 可以很方便的进行数据库的移植工作。

  • 提供了缓存机制,是程序执行更改的高效。

114. 什么是 ORM 框架?

ORM(Object Relation Mapping)对象关系映射,是把数据库中的关系数据映射成为程序中的对象。

使用 ORM 的优点:提高了开发效率降低了开发成本、开发更简单更对象化、可移植更强。

115. hibernate 中如何在控制台查看打印的 SQL 语句?

在 Config 里面把 hibernate. show\SQL 设置为 true 就可以。但不建议开启,开启之后会降低程序的运行效率。

116. hibernate 有几种查询方式?

三种:hql、原生 SQL、条件查询 Criteria。

117. hibernate 实体类可以被定义为 final 吗?

实体类可以定义为 final 类,但这样的话就不能使用 hibernate 代理模式下的延迟关联提供性能了,所以不建议定义实体类为 final。

118. 在 hibernate 中使用 Integer 和 int 做映射有什么区别?

Integer 类型为对象,它的值允许为 null,而 int 属于基础数据类型,值不能为 null。

119. hibernate 是如何工作的?

  • 读取并解析配置文件。

  • 读取并解析映射文件,创建 SessionFactory。

  • 打开 Session。

  • 创建事务。

  • 进行持久化操作。

  • 提交事务。

  • 关闭 Session。

  • 关闭 SessionFactory。

120. get()和 load()的区别?

  • 数据查询时,没有 OID 指定的对象,get() 返回 null;load() 返回一个代理对象。

  • load()支持延迟加载;get() 不支持延迟加载。

121. 说一下 hibernate 的缓存机制?

hibernate 常用的缓存有一级缓存和二级缓存:

一级缓存:也叫 Session 缓存,只在 Session 作用范围内有效,不需要用户干涉,由 hibernate 自身维护,可以通过:evict(object)清除 object 的缓存;clear()清除一级缓存中的所有缓存;flush()刷出缓存;

二级缓存:应用级别的缓存,在所有 Session 中都有效,支持配置第三方的缓存,如:EhCache。

122. hibernate 对象有哪些状态?

  • 临时/瞬时状态:直接 new 出来的对象,该对象还没被持久化(没保存在数据库中),不受 Session 管理。

  • 持久化状态:当调用 Session 的 save/saveOrupdate/get/load/list 等方法的时候,对象就是持久化状态。

  • 游离状态:Session 关闭之后对象就是游离状态。

123. 在 hibernate 中 getCurrentSession 和 openSession 的区别是什么?

  • getCurrentSession 会绑定当前线程,而 openSession 则不会。

  • getCurrentSession 事务是 Spring 控制的,并且不需要手动关闭,而 openSession 需要我们自己手动开启和提交事务。

124. hibernate 实体类必须要有无参构造函数吗?为什么?

hibernate 中每个实体类必须提供一个无参构造函数,因为 hibernate 框架要使用 reflection api,通过调用 ClassnewInstance() 来创建实体类的实例,如果没有无参的构造函数就会抛出异常。

MyBatis

125. MyBatis 中 #{}和 ${}的区别是什么?

\#{}是预编译处理,${}是字符替换。 在使用 #{}时,MyBatis 会将 SQL 中的 #{}替换成"?",配合 PreparedStatement 的 set 方法赋值,这样可以有效的防止 SQL 注入,保证程序的运行安全。

126. MyBatis 有几种分页方式?

分页方式:逻辑分页和物理分页。

*逻辑分页:* 使用 MyBatis 自带的 RowBounds 进行分页,它是一次性查询很多数据,然后在数据中再进行检索。

*物理分页:* 自己手写 SQL 分页或使用分页插件 PageHelper,去数据库查询指定条数的分页数据的形式。

127. RowBounds 是一次性查询全部结果吗?为什么?

RowBounds 表面是在"所有"数据中检索数据,其实并非是一次性查询出所有数据,因为 MyBatis 是对 jdbc 的封装,在 jdbc 驱动中有一个 Fetch Size 的配置,它规定了每次最多从数据库查询多少条数据,假如你要查询更多数据,它会在你执行 next()的时候,去查询更多的数据。就好比你去自动取款机取 10000 元,但取款机每次最多能取 2500 元,所以你要取 4 次才能把钱取完。只是对于 jdbc 来说,当你调用 next()的时候会自动帮你完成查询工作。这样做的好处可以有效的防止内存溢出。

Fetch Size 官方相关文档:http://t. cn/EfSE2g3

128. MyBatis 逻辑分页和物理分页的区别是什么?

  • 逻辑分页是一次性查询很多数据,然后再在结果中检索分页的数据。这样做弊端是需要消耗大量的内存、有内存溢出的风险、对数据库压力较大。

  • 物理分页是从数据库查询指定条数的数据,弥补了一次性全部查出的所有数据的种种缺点,比如需要大量的内存,对数据库查询压力较大等问题。

129. MyBatis 是否支持延迟加载?延迟加载的原理是什么?

MyBatis 支持延迟加载,设置 lazyLoadingEnabled=true 即可。

延迟加载的原理的是调用的时候触发加载,而不是在初始化的时候就加载信息。比如调用

  1. getB(). getName(),这个时候发现 a. getB() 的值为

null,此时会单独触发事先保存好的关联 B 对象的 SQL,先查询出来 B,然后再调用 a. setB(b),而这时候再调用 a. getB(). getName() 就有值了,这就是延迟加载的基本原理。

130. 说一下 MyBatis 的一级缓存和二级缓存?

  • 一级缓存:基于 PerpetualCache 的 HashMap 本地缓存,它的声明周期是和 SQLSession 一致的,有多个 SQLSession 或者分布式的环境中数据库操作,可能会出现脏数据。当 Session flush 或 close 之后,该 Session 中的所有 Cache 就将清空,默认一级缓存是开启的。

  • 二级缓存:也是基于 PerpetualCache 的 HashMap 本地缓存,不同在于其存储作用域为 Mapper 级别的,如果多个SQLSession之间需要共享缓存,则需要使用到二级缓存,并且二级缓存可自定义存储源,如 Ehcache。默认不打开二级缓存,要开启二级缓存,使用二级缓存属性类需要实现 Serializable 序列化接口(可用来保存对象的状态)。

开启二级缓存数据查询流程:二级缓存 -> 一级缓存 -> 数据库。

缓存更新机制:当某一个作用域(一级缓存 Session/二级缓存 Mapper)进行了C/U/D 操作后,默认该作用域下所有 select 中的缓存将被 clear。

131. MyBatis 和 hibernate 的区别有哪些?

  • 灵活性:MyBatis 更加灵活,自己可以写 SQL 语句,使用起来比较方便。

  • 可移植性:MyBatis 有很多自己写的 SQL,因为每个数据库的 SQL 可以不相同,所以可移植性比较差。

  • 学习和使用门槛:MyBatis 入门比较简单,使用门槛也更低。

  • 二级缓存:hibernate 拥有更好的二级缓存,它的二级缓存可以自行更换为第三方的二级缓存。

132. MyBatis 有哪些执行器(Executor)?

MyBatis 有三种基本的Executor执行器:

  • SimpleExecutor:每执行一次 update 或 select 就开启一个 Statement 对象,用完立刻关闭 Statement 对象;

  • ReuseExecutor:执行 update 或 select,以 SQL 作为 key 查找 Statement 对象,存在就使用,不存在就创建,用完后不关闭 Statement 对象,而是放置于 Map 内供下一次使用。简言之,就是重复使用 Statement 对象;

  • BatchExecutor:执行 update(没有 select,jdbc 批处理不支持 select),将所有 SQL 都添加到批处理中(addBatch()),等待统一执行(executeBatch()),它缓存了多个 Statement 对象,每个 Statement 对象都是 addBatch()完毕后,等待逐一执行 executeBatch()批处理,与 jdbc 批处理相同。

133. MyBatis 分页插件的实现原理是什么?

分页插件的基本原理是使用 MyBatis 提供的插件接口,实现自定义插件,在插件的拦截方法内拦截待执行的 SQL,然后重写 SQL,根据 dialect 方言,添加对应的物理分页语句和物理分页参数。

134. MyBatis 如何编写一个自定义插件?

自定义插件实现原理

MyBatis 自定义插件针对 MyBatis 四大对象(Executor、StatementHandler、ParameterHandler、ResultSetHandler)进行拦截:

  • Executor:拦截内部执行器,它负责调用 StatementHandler 操作数据库,并把结果集通过 ResultSetHandler 进行自动映射,另外它还处理了二级缓存的操作;

  • StatementHandler:拦截 SQL 语法构建的处理,它是 MyBatis 直接和数据库执行 SQL 脚本的对象,另外它也实现了 MyBatis 的一级缓存;

  • ParameterHandler:拦截参数的处理;

  • ResultSetHandler:拦截结果集的处理。

自定义插件实现关键

MyBatis 插件要实现 Interceptor 接口,接口包含的方法,如下:

public interface Interceptor {

Object *intercept*(Invocation invocation) throws Throwable;

Object *plugin*(Object target);

void *setProperties*(Properties properties);

}

  • setProperties 方法是在 MyBatis 进行配置插件的时候可以配置自定义相关属性,即:接口实现对象的参数配置;

  • plugin 方法是插件用于封装目标对象的,通过该方法我们可以返回目标对象本身,也可以返回一个它的代理,可以决定是否要进行拦截进而决定要返回一个什么样的目标对象,官方提供了示例:return Plugin. wrap(target, this);

  • intercept 方法就是要进行拦截的时候要执行的方法。

自定义插件实现示例

官方插件实现:

@Intercepts({@Signature(type = Executor. class, method = "query",

args = {MappedStatement. class, Object. class, RowBounds. class, ResultHandler. class})})

public class TestInterceptor implements Interceptor {

public Object *intercept*(Invocation invocation) throws Throwable {

Object target = invocation. getTarget(); //被代理对象

Method method = invocation. getMethod(); //代理方法

Object[] args = invocation. getArgs(); //方法参数

/ do something . . . . . . 方法拦截前执行代码块/

Object result = invocation. proceed();

/ do something . . . . . . . 方法拦截后执行代码块/

return result;

}

public Object *plugin*(Object target) {

return Plugin. wrap(target, this);

}

}

RabbitMQ

135. RabbitMQ 的使用场景有哪些?

  • 抢购活动,削峰填谷,防止系统崩塌。

  • 延迟信息处理,比如 10 分钟之后给下单未付款的用户发送邮件提醒。

  • 解耦系统,对于新增的功能可以单独写模块扩展,比如用户确认评价之后,新增了给用户返积分的功能,这个时候不用在业务代码里添加新增积分的功能,只需要把新增积分的接口订阅确认评价的消息队列即可,后面再添加任何功能只需要订阅对应的消息队列即可。

136. RabbitMQ 有哪些重要的角色?

RabbitMQ 中重要的角色有:生产者、消费者和代理:

  • 生产者:消息的创建者,负责创建和推送数据到消息服务器;

  • 消费者:消息的接收方,用于处理数据和确认消息;

  • 代理:就是 RabbitMQ 本身,用于扮演“快递”的角色,本身不生产消息,只是扮演“快递”的角色。

137. RabbitMQ 有哪些重要的组件?

  • ConnectionFactory(连接管理器):应用程序与Rabbit之间建立连接的管理器,程序代码中使用。

  • Channel(信道):消息推送使用的通道。

  • Exchange(交换器):用于接受、分配消息。

  • Queue(队列):用于存储生产者的消息。

  • RoutingKey(路由键):用于把生成者的数据分配到交换器上。

  • BindingKey(绑定键):用于把交换器的消息绑定到队列上。

138. RabbitMQ 中 vhost 的作用是什么?

vhost:每个 RabbitMQ 都能创建很多 vhost,我们称之为虚拟主机,每个虚拟主机其实都是 mini 版的RabbitMQ,它拥有自己的队列,交换器和绑定,拥有自己的权限机制。

139. RabbitMQ 的消息是怎么发送的?

首先客户端必须连接到 RabbitMQ 服务器才能发布和消费消息,客户端和 rabbit server 之间会创建一个 tcp 连接,一旦 tcp 打开并通过了认证(认证就是你发送给 rabbit 服务器的用户名和密码),你的客户端和 RabbitMQ 就创建了一条 amqp 信道(channel),信道是创建在"真实" tcp 上的虚拟连接,amqp 命令都是通过信道发送出去的,每个信道都会有一个唯一的 id,不论是发布消息,订阅队列都是通过这个信道完成的。

140. RabbitMQ 怎么保证消息的稳定性?

  • 提供了事务的功能。

  • 通过将 channel 设置为 confirm(确认)模式。

141. RabbitMQ 怎么避免消息丢失?

  • 把消息持久化磁盘,保证服务器重启消息不丢失。

  • 每个集群中至少有一个物理磁盘,保证消息落入磁盘。

142. 要保证消息持久化成功的条件有哪些?

  • 声明队列必须设置持久化 durable 设置为 true.

  • 消息推送投递模式必须设置持久化,deliveryMode 设置为 2(持久)。

  • 消息已经到达持久化交换器。

  • 消息已经到达持久化队列。

以上四个条件都满足才能保证消息持久化成功。

143. RabbitMQ 持久化有什么缺点?

持久化的缺地就是降低了服务器的吞吐量,因为使用的是磁盘而非内存存储,从而降低了吞吐量。可尽量使用 ssd 硬盘来缓解吞吐量的问题。

144. RabbitMQ 有几种广播类型?

  • direct(默认方式):最基础最简单的模式,发送方把消息发送给订阅方,如果有多个订阅者,默认采取轮询的方式进行消息发送。

  • headers:与 direct 类似,只是性能很差,此类型几乎用不到。

  • fanout:分发模式,把消费分发给所有订阅者。

  • topic:匹配订阅模式,使用正则匹配到消息队列,能匹配到的都能接收到。

145. RabbitMQ 怎么实现延迟消息队列?

延迟队列的实现有两种方式:

  • 通过消息过期后进入死信交换器,再由交换器转发到延迟消费队列,实现延迟功能;

  • 使用 RabbitMQ-delayed-message-exchange 插件实现延迟功能。

146. RabbitMQ 集群有什么用?

集群主要有以下两个用途:

  • 高可用:某个服务器出现问题,整个 RabbitMQ 还可以继续使用;

  • 高容量:集群可以承载更多的消息量。

147. RabbitMQ 节点的类型有哪些?

  • 磁盘节点:消息会存储到磁盘。

  • 内存节点:消息都存储在内存中,重启服务器消息丢失,性能高于磁盘类型。

148. RabbitMQ 集群搭建需要注意哪些问题?

  • 各节点之间使用“--link”连接,此属性不能忽略。

  • 各节点使用的 erlang cookie 值必须相同,此值相当于“秘钥”的功能,用于各节点的认证。

  • 整个集群中必须包含一个磁盘节点。

149. RabbitMQ 每个节点是其他节点的完整拷贝吗?为什么?

不是,原因有以下两个:

  • 存储空间的考虑:如果每个节点都拥有所有队列的完全拷贝,这样新增节点不但没有新增存储空间,反而增加了更多的冗余数据;

  • 性能的考虑:如果每条消息都需要完整拷贝到每一个集群节点,那新增节点并没有提升处理消息的能力,最多是保持和单节点相同的性能甚至是更糟。

150. RabbitMQ 集群中唯一一个磁盘节点崩溃了会发生什么情况?

如果唯一磁盘的磁盘节点崩溃了,不能进行以下操作:

  • 不能创建队列

  • 不能创建交换器

  • 不能创建绑定

  • 不能添加用户

  • 不能更改权限

  • 不能添加和删除集群节点

唯一磁盘节点崩溃了,集群是可以保持运行的,但你不能更改任何东西。

151. RabbitMQ 对集群节点停止顺序有要求吗?

RabbitMQ 对集群的停止的顺序是有要求的,应该先关闭内存节点,最后再关闭磁盘节点。如果顺序恰好相反的话,可能会造成消息的丢失。

Kafka

152. kafka 可以脱离 zookeeper 单独使用吗?为什么?

kafka 不能脱离 zookeeper 单独使用,因为 kafka 使用 zookeeper 管理和协调 kafka 的节点服务器。

153. kafka 有几种数据保留的策略?

kafka 有两种数据保存策略:按照过期时间保留和按照存储的消息大小保留。

154. kafka 同时设置了 7 天和 10G 清除数据,到第五天的时候消息达到了

10G,这个时候 kafka 将如何处理?

这个时候 kafka 会执行数据清除工作,时间和大小不论那个满足条件,都会清空数据。

155. 什么情况会导致 kafka 运行变慢?

  • cpu 性能瓶颈

  • 磁盘读写瓶颈

  • 网络瓶颈

156. 使用 kafka 集群需要注意什么?

  • 集群的数量不是越多越好,最好不要超过 7 个,因为节点越多,消息复制需要的时间就越长,整个群组的吞吐量就越低。

  • 集群数量最好是单数,因为超过一半故障集群就不能用了,设置为单数容错率更高。

Zookeeper

157. zookeeper 是什么?

zookeeper 是一个分布式的,开放源码的分布式应用程序协调服务,是 google chubby 的开源实现,是 hadoop 和 hbase 的重要组件。它是一个为分布式应用提供一致性服务的软件,提供的功能包括:配置维护、域名服务、分布式同步、组服务等。

158. zookeeper 都有哪些功能?

  • 集群管理:监控节点存活状态、运行请求等。

  • 主节点选举:主节点挂掉了之后可以从备用的节点开始新一轮选主,主节点选举说的就是这个选举的过程,使用 zookeeper 可以协助完成这个过程。

  • 分布式锁:zookeeper 提供两种锁:独占锁、共享锁。独占锁即一次只能有一个线程使用资源,共享锁是读锁共享,读写互斥,即可以有多线线程同时读同一个资源,如果要使用写锁也只能有一个线程使用。zookeeper可以对分布式锁进行控制。

  • 命名服务:在分布式系统中,通过使用命名服务,客户端应用能够根据指定名字来获取资源或服务的地址,提供者等信息。

159. zookeeper 有几种部署模式?

zookeeper 有三种部署模式:

  • 单机部署:一台集群上运行;

  • 集群部署:多台集群运行;

  • 伪集群部署:一台集群启动多个 zookeeper 实例运行。

160. zookeeper 怎么保证主从节点的状态同步?

zookeeper 的核心是原子广播,这个机制保证了各个 server 之间的同步。实现这个机制的协议叫做 zab 协议。 zab 协议有两种模式,分别是恢复模式(选主)和广播模式(同步)。当服务启动或者在领导者崩溃后,zab 就进入了恢复模式,当领导者被选举出来,且大多数 server 完成了和 leader 的状态同步以后,恢复模式就结束了。状态同步保证了 leader 和 server 具有相同的系统状态。

161. 集群中为什么要有主节点?

在分布式环境中,有些业务逻辑只需要集群中的某一台机器进行执行,其他的机器可以共享这个结果,这样可以大大减少重复计算,提高性能,所以就需要主节点。

  1. 集群中有 3 台服务器,其中一个节点宕机,这个时候 zookeeper

还可以使用吗?

可以继续使用,单数服务器只要没超过一半的服务器宕机就可以继续使用。

163. 说一下 zookeeper 的通知机制?

客户端端会对某个 znode 建立一个 watcher 事件,当该 znode 发生变化时,这些客户端会收到 zookeeper 的通知,然后客户端可以根据 znode 变化来做出业务上的改变。

MySQL

164. 数据库的三范式是什么?

  • 第一范式:强调的是列的原子性,即数据库表的每一列都是不可分割的原子数据项。

  • 第二范式:要求实体的属性完全依赖于主关键字。所谓完全依赖是指不能存在仅依赖主关键字一部分的属性。

  • 第三范式:任何非主属性不依赖于其它非主属性。

165. 一张自增表里面总共有 7 条数据,删除了最后 2 条数据,重启 MySQL

数据库,又插入了一条数据,此时 id 是几?

  • 表类型如果是 MyISAM ,那 id 就是 8。

  • 表类型如果是 InnoDB,那 id 就是 6。

InnoDB 表只会把自增主键的最大 id 记录在内存中,所以重启之后会导致最大 id 丢失。

166. 如何获取当前数据库版本?

使用 select version() 获取当前 MySQL 数据库版本。

167. 说一下 ACID 是什么?

  • Atomicity(原子性):一个事务(transaction)中的所有操作,或者全部完成,或者全部不完成,不会结束在中间某个环节。事务在执行过程中发生错误,会被恢复(Rollback)到事务开始前的状态,就像这个事务从来没有执行过一样。即,事务不可分割、不可约简。

  • Consistency(一致性):在事务开始之前和事务结束以后,数据库的完整性没有被破坏。这表示写入的资料必须完全符合所有的预设约束、触发器、级联回滚等。

  • Isolation(隔离性):数据库允许多个并发事务同时对其数据进行读写和修改的能力,隔离性可以防止多个事务并发执行时由于交叉执行而导致数据的不一致。事务隔离分为不同级别,包括读未提交(Read uncommitted)、读提交(read committed)、可重复读(repeatable read)和串行化(Serializable)。

  • Durability(持久性):事务处理结束后,对数据的修改就是永久的,即便系统故障也不会丢失。

168. char 和 varchar 的区别是什么?

  • char(n) :固定长度类型,比如订阅 char(10),当你输入"abc"三个字符的时候,它们占的空间还是 10 个字节,其他 7 个是空字节。

chat 优点:效率高;缺点:占用空间;适用场景:存储密码的 md5 值,固定长度的,使用 char 非常合适。

  • varchar(n) :可变长度,存储的值是每个值占用的字节再加上一个用来记录其长度的字节的长度。

所以,从空间上考虑 varcahr 比较合适;从效率上考虑 char 比较合适,二者使用需要权衡。

169. float 和 double 的区别是什么?

  • float 最多可以存储 8 位的十进制数,并在内存中占 4 字节。

  • double 最可可以存储 16 位的十进制数,并在内存中占 8 字节。

170. MySQL 的内连接、左连接、右连接有什么区别?

内连接关键字:inner join;左连接:left join;右连接:right join。

内连接是把匹配的关联数据显示出来;左连接是左边的表全部显示出来,右边的表显示出符合条件的数据;右连接正好相反。

171. MySQL 索引是怎么实现的?

索引是满足某种特定查找算法的数据结构,而这些数据结构会以某种方式指向数据,从而实现高效查找数据。

具体来说 MySQL 中的索引,不同的数据引擎实现有所不同,但目前主流的数据库引擎的索引都是 B+ 树实现的,B+ 树的搜索效率,可以到达二分法的性能,找到数据区域之后就找到了完整的数据结构了,所有索引的性能也是更好的。

172. 怎么验证 MySQL 的索引是否满足需求?

使用 explain 查看 SQL 是如何执行查询语句的,从而分析你的索引是否满足需求。

explain 语法:explain select * from table where type=1。

173. 说一下数据库的事务隔离?

MySQL 的事务隔离是在 MySQL. ini 配置文件里添加的,在文件的最后添加:

transaction-isolation = REPEATABLE-READ

可用的配置值:READ-UNCOMMITTED、READ-COMMITTED、REPEATABLE-READ、SERIALIZABLE。

  • READ-UNCOMMITTED:未提交读,最低隔离级别、事务未提交前,就可被其他事务读取(会出现幻读、脏读、不可重复读)。

  • READ-COMMITTED:提交读,一个事务提交后才能被其他事务读取到(会造成幻读、不可重复读)。

  • REPEATABLE-READ:可重复读,默认级别,保证多次读取同一个数据时,其值都和事务开始时候的内容是一致,禁止读取到别的事务未提交的数据(会造成幻读)。

  • SERIALIZABLE:序列化,代价最高最可靠的隔离级别,该隔离级别能防止脏读、不可重复读、幻读。

*脏读* :表示一个事务能够读取另一个事务中还未提交的数据。比如,某个事务尝试插入记录 A,此时该事务还未提交,然后另一个事务尝试读取到了记录 A。

*不可重复读* :是指在一个事务内,多次读同一数据。

*幻读* :指同一个事务内多次查询返回的结果集不一样。比如同一个事务 A 第一次查询时候有 n 条记录,但是第二次同等条件下查询却有 n+1 条记录,这就好像产生了幻觉。发生幻读的原因也是另外一个事务新增或者删除或者修改了第一个事务结果集里面的数据,同一个记录的数据内容被修改了,所有数据行的记录就变多或者变少了。

174. 说一下 MySQL 常用的引擎?

  • InnoDB 引擎:mysql 5.1 后默认的数据库引擎,提供了对数据库 acid 事务的支持,并且还提供了行级锁和外键的约束,它的设计的目标就是处理大数据容量的数据库系统。MySQL 运行的时候,InnoDB 会在内存中建立缓冲池,用于缓冲数据和索引。但是该引擎是不支持全文搜索,同时启动也比较的慢,它是不会保存表的行数的,所以当进行 select count(*) from table 指令的时候,需要进行扫描全表。由于锁的粒度小,写操作是不会锁定全表的,所以在并发度较高的场景下使用会提升效率的。

  • MyIASM 引擎:不提供事务的支持,也不支持行级锁和外键。因此当执行插入和更新语句时,即执行写操作的时候需要锁定这个表,所以会导致效率会降低。不过和 InnoDB 不同的是,MyIASM 引擎是保存了表的行数,于是当进行 select count(*) from table 语句时,可以直接的读取已经保存的值而不需要进行扫描全表。所以,如果表的读操作远远多于写操作时,并且不需要事务的支持的,可以将 MyIASM 作为数据库引擎的首选。

175. 说一下 MySQL 的行锁和表锁?

MyISAM 只支持表锁,InnoDB 支持表锁和行锁,默认为行锁。

  • 表级锁:开销小,加锁快,不会出现死锁。锁定粒度大,发生锁冲突的概率最高,并发量最低。

  • 行级锁:开销大,加锁慢,会出现死锁。锁力度小,发生锁冲突的概率小,并发度最高。

176. 说一下乐观锁和悲观锁?

  • 乐观锁:每次去拿数据的时候都认为别人不会修改,所以不会上锁,但是在提交更新的时候会判断一下在此期间别人有没有去更新这个数据。

  • 悲观锁:每次去拿数据的时候都认为别人会修改,所以每次在拿数据的时候都会上锁,这样别人想拿这个数据就会阻止,直到这个锁被释放。

数据库的乐观锁需要自己实现,在表里面添加一个 version 字段,每次修改成功值加 1,这样每次修改的时候先对比一下,自己拥有的 version 和数据库现在的 version 是否一致,如果不一致就不修改,这样就实现了乐观锁。

177. MySQL 问题排查都有哪些手段?

  • 使用 show processlist 命令查看当前所有连接信息。

  • 使用 explain 命令查询 SQL 语句执行计划。

  • 开启慢查询日志,查看慢查询的 SQL。

178. 如何做 MySQL 的性能优化?

  • 为搜索字段创建索引。

  • 避免使用 select *,列出需要查询的字段。

  • 垂直分割分表。

  • 选择正确的存储引擎。

Redis

179. Redis 是什么?都有哪些使用场景?

Redis 是一个使用 C 语言开发的高速缓存数据库。

Redis 使用场景:

  • 记录帖子点赞数、点击数、评论数;

  • 缓存近期热帖;

  • 缓存文章详情信息;

  • 记录用户会话信息。

180. Redis 有哪些功能?

  • 数据缓存功能

  • 分布式锁的功能

  • 支持数据持久化

  • 支持事务

  • 支持消息队列

181. Redis 和 memcache 有什么区别?

  • 存储方式不同:memcache 把数据全部存在内存之中,断电后会挂掉,数据不能超过内存大小;Redis 有部份存在硬盘上,这样能保证数据的持久性。

  • 数据支持类型:memcache 对数据类型支持相对简单;Redis 有复杂的数据类型。

  • 使用底层模型不同:它们之间底层实现方式,以及与客户端之间通信的应用协议不一样,Redis 自己构建了 vm 机制,因为一般的系统调用系统函数的话,会浪费一定的时间去移动和请求。

  • value 值大小不同:Redis 最大可以达到 512mb;memcache 只有 1mb。

182. Redis 为什么是单线程的?

因为 cpu 不是 Redis 的瓶颈,Redis 的瓶颈最有可能是机器内存或者网络带宽。既然单线程容易实现,而且 cpu 又不会成为瓶颈,那就顺理成章地采用单线程的方案了。

关于 Redis 的性能,官方网站也有,普通笔记本轻松处理每秒几十万的请求。

而且单线程并不代表就慢 nginx 和 nodejs 也都是高性能单线程的代表。

  1. 什么是缓存穿透?怎么解决?

缓存穿透:指查询一个一定不存在的数据,由于缓存是不命中时需要从数据库查询,查不到数据则不写入缓存,这将导致这个不存在的数据每次请求都要到数据库去查询,造成缓存穿透。

解决方案:最简单粗暴的方法如果一个查询返回的数据为空(不管是数据不存在,还是系统故障),我们就把这个空结果进行缓存,但它的过期时间会很短,最长不超过五分钟。

184. Redis 支持的数据类型有哪些?

Redis 支持的数据类型:string(字符串)、list(列表)、hash(字典)、set(集合)、zset(有序集合)。

185. Redis 支持的 Java 客户端都有哪些?

支持的 Java 客户端有 Redisson、jedis、lettuce 等。

186. jedis 和 Redisson 有哪些区别?

  • jedis:提供了比较全面的 Redis 命令的支持。

  • Redisson:实现了分布式和可扩展的 Java 数据结构,与 jedis 相比 Redisson 的功能相对简单,不支持排序、事务、管道、分区等 Redis 特性。

187. 怎么保证缓存和数据库数据的一致性?

  • 合理设置缓存的过期时间。

  • 新增、更改、删除数据库操作时同步更新 Redis,可以使用事物机制来保证数据的一致性。

188. Redis 持久化有几种方式?

Redis 的持久化有两种方式,或者说有两种策略:

  • RDB(Redis Database):指定的时间间隔能对你的数据进行快照存储。

  • AOF(Append Only File):每一个收到的写命令都通过write函数追加到文件中。

189. Redis 怎么实现分布式锁?

Redis 分布式锁其实就是在系统里面占一个"坑",其他程序也要占"坑"的时候,占用成功了就可以继续执行,失败了就只能放弃或稍后重试。

占坑一般使用 setnx(set if not exists)指令,只允许被一个程序占有,使用完调用 del 释放锁。

  1. Redis 分布式锁有什么缺陷?

Redis 分布式锁不能解决超时的问题,分布式锁有一个超时时间,程序的执行如果超出了锁的超时时间就会出现问题。

191. Redis 如何做内存优化?

尽量使用 Redis 的散列表,把相关的信息放到散列表里面存储,而不是把每个字段单独存储,这样可以有效的减少内存使用。比如将 Web 系统的用户对象,应该放到散列表里面再整体存储到 Redis,而不是把用户的姓名、年龄、密码、邮箱等字段分别设置 key 进行存储。

192. Redis 淘汰策略有哪些?

  • volatile-lru:从已设置过期时间的数据集(server. db[i]. expires)中挑选最近最少使用的数据淘汰。

  • volatile-ttl:从已设置过期时间的数据集(server. db[i]. expires)中挑选将要过期的数据淘汰。

  • volatile-random:从已设置过期时间的数据集(server. db[i]. expires)中任意选择数据淘汰。

  • allkeys-lru:从数据集(server. db[i]. dict)中挑选最近最少使用的数据淘汰。

  • allkeys-random:从数据集(server. db[i]. dict)中任意选择数据淘汰。

  • no-enviction(驱逐):禁止驱逐数据。

193. Redis 常见的性能问题有哪些?该如何解决?

  • 主服务器写内存快照,会阻塞主线程的工作,当快照比较大时对性能影响是非常大的,会间断性暂停服务,所以主服务器最好不要写内存快照。

  • Redis 主从复制的性能问题,为了主从复制的速度和连接的稳定性,主从库最好在同一个局域网内。

JVM

194. 说一下 JVM 的主要组成部分?及其作用?

  • 类加载器(ClassLoader)

  • 运行时数据区(Runtime Data Area)

  • 执行引擎(Execution Engine)

  • 本地库接口(Native Interface)

*组件的作用:* 首先通过类加载器(ClassLoader)会把 Java 代码转换成字节码,运行时数据区(Runtime Data Area)再把字节码加载到内存中,而字节码文件只是 JVM 的一套指令集规范,并不能直接交给底层操作系统去执行,因此需要特定的命令解析器执行引擎(Execution Engine),将字节码翻译成底层系统指令,再交由 CPU 去执行,而这个过程中需要调用其他语言的本地库接口(Native Interface)来实现整个程序的功能。

195. 说一下 JVM 运行时数据区?

不同虚拟机的运行时数据区可能略微有所不同,但都会遵从 Java 虚拟机规范, Java 虚拟机规范规定的区域分为以下 5 个部分:

  • 程序计数器(Program Counter Register):当前线程所执行的字节码的行号指示器,字节码解析器的工作是通过改变这个计数器的值,来选取下一条需要执行的字节码指令,分支、循环、跳转、异常处理、线程恢复等基础功能,都需要依赖这个计数器来完成;

  • Java 虚拟机栈(Java Virtual Machine Stacks):用于存储局部变量表、操作数栈、动态链接、方法出口等信息;

  • 本地方法栈(Native Method Stack):与虚拟机栈的作用是一样的,只不过虚拟机栈是服务 Java 方法的,而本地方法栈是为虚拟机调用 Native 方法服务的;

  • Java 堆(Java Heap):Java 虚拟机中内存最大的一块,是被所有线程共享的,几乎所有的对象实例都在这里分配内存;

  • 方法区(Methed Area):用于存储已被虚拟机加载的类信息、常量、静态变量、即时编译后的代码等数据。

196. 说一下堆栈的区别?

  • 功能方面:堆是用来存放对象的,栈是用来执行程序的。

  • 共享性:堆是线程共享的,栈是线程私有的。

  • 空间大小:堆大小远远大于栈。

197. 队列和栈是什么?有什么区别?

队列和栈都是被用来预存储数据的。

队列允许先进先出检索元素,但也有例外的情况,Deque 接口允许从两端检索元素。

栈和队列很相似,但它运行对元素进行后进先出进行检索。

198. 什么是双亲委派模型?

在介绍双亲委派模型之前先说下类加载器。对于任意一个类,都需要由加载它的类加载器和这个类本身一同确立在 JVM 中的唯一性,每一个类加载器,都有一个独立的类名称空间。类加载器就是根据指定全限定名称将 class 文件加载到 JVM 内存,然后再转化为 class 对象。

类加载器分类:

  • 启动类加载器(Bootstrap ClassLoader),是虚拟机自身的一部分,用来加载Java_HOME/lib/目录中的,或者被 -Xbootclasspath 参数所指定的路径中并且被虚拟机识别的类库;

  • 其他类加载器:

  • 扩展类加载器(Extension ClassLoader):负责加载<java_home style="box-sizing: border-box; outline: 0px !important;">\lib\ext目录或Java. ext. dirs系统变量指定的路径中的所有类库;

  • 应用程序类加载器(Application ClassLoader)。负责加载用户类路径(classpath)上的指定类库,我们可以直接使用这个类加载器。一般情况,如果我们没有自定义类加载器默认就是用这个加载器。

双亲委派模型:如果一个类加载器收到了类加载的请求,它首先不会自己去加载这个类,而是把这个请求委派给父类加载器去完成,每一层的类加载器都是如此,这样所有的加载请求都会被传送到顶层的启动类加载器中,只有当父加载无法完成加载请求(它的搜索范围中没找到所需的类)时,子加载器才会尝试去加载类。

199. 说一下类装载的执行过程?

类装载分为以下 5 个步骤:

  • 加载:根据查找路径找到相应的 class 文件然后导入;

  • 检查:检查加载的 class 文件的正确性;

  • 准备:给类中的静态变量分配内存空间;

  • 解析:虚拟机将常量池中的符号引用替换成直接引用的过程。符号引用就理解为一个标示,而在直接引用直接指向内存中的地址;

  • 初始化:对静态变量和静态代码块执行初始化工作。

200. 怎么判断对象是否可以被回收?

一般有两种方法来判断:

  • 引用计数器:为每个对象创建一个引用计数,有对象引用时计数器 +1,引用被释放时计数 -1,当计数器为 0 时就可以被回收。它有一个缺点不能解决循环引用的问题;

  • 可达性分析:从 GC Roots 开始向下搜索,搜索所走过的路径称为引用链。当一个对象到 GC Roots 没有任何引用链相连时,则证明此对象是可以被回收的。

201. Java 中都有哪些引用类型?

  • 强引用:发生 gc 的时候不会被回收。

  • 软引用:有用但不是必须的对象,在发生内存溢出之前会被回收。

  • 弱引用:有用但不是必须的对象,在下一次GC时会被回收。

  • 虚引用(幽灵引用/幻影引用):无法通过虚引用获得对象,用 PhantomReference 实现虚引用,虚引用的用途是在 gc 时返回一个通知。

202. 说一下 JVM 有哪些垃圾回收算法?

  • 标记-清除算法:标记无用对象,然后进行清除回收。缺点:效率不高,无法清除垃圾碎片。

  • 标记-整理算法:标记无用对象,让所有存活的对象都向一端移动,然后直接清除掉端边界以外的内存。

  • 复制算法:按照容量划分二个大小相等的内存区域,当一块用完的时候将活着的对象复制到另一块上,然后再把已使用的内存空间一次清理掉。缺点:内存使用率不高,只有原来的一半。

  • 分代算法:根据对象存活周期的不同将内存划分为几块,一般是新生代和老年代,新生代基本采用复制算法,老年代采用标记整理算法。

203. 说一下 JVM 有哪些垃圾回收器?

  • Serial:最早的单线程串行垃圾回收器。

  • Serial Old:Serial 垃圾回收器的老年版本,同样也是单线程的,可以作为 CMS 垃圾回收器的备选预案。

  • ParNew:是 Serial 的多线程版本。

  • Parallel 和 ParNew 收集器类似是多线程的,但 Parallel 是吞吐量优先的收集器,可以牺牲等待时间换取系统的吞吐量。

  • Parallel Old 是 Parallel 老生代版本,Parallel 使用的是复制的内存回收算法,Parallel Old 使用的是标记-整理的内存回收算法。

  • CMS:一种以获得最短停顿时间为目标的收集器,非常适用 B/S 系统。

  • G1:一种兼顾吞吐量和停顿时间的 GC 实现,是 JDK 9 以后的默认 GC 选项。

204. 详细介绍一下 CMS 垃圾回收器?

CMS 是英文 Concurrent Mark-Sweep 的简称,是以牺牲吞吐量为代价来获得最短回收停顿时间的垃圾回收器。对于要求服务器响应速度的应用上,这种垃圾回收器非常适合。在启动 JVM 的参数加上"-XX:+UseConcMarkSweepGC"来指定使用 CMS 垃圾回收器。

CMS 使用的是标记-清除的算法实现的,所以在 gc 的时候回产生大量的内存碎片,当剩余内存不能满足程序运行要求时,系统将会出现 Concurrent Mode Failure,临时 CMS 会采用 Serial Old 回收器进行垃圾清除,此时的性能将会被降低。

205. 新生代垃圾回收器和老生代垃圾回收器都有哪些?有什么区别?

  • 新生代回收器:Serial、ParNew、Parallel Scavenge

  • 老年代回收器:Serial Old、Parallel Old、CMS

  • 整堆回收器:G1

新生代垃圾回收器一般采用的是复制算法,复制算法的优点是效率高,缺点是内存利用率低;老年代回收器一般采用的是标记-整理的算法进行垃圾回收。

206. 简述分代垃圾回收器是怎么工作的?

分代回收器有两个分区:老生代和新生代,新生代默认的空间占比总空间的 1/3,老生代的默认占比是 2/3。

新生代使用的是复制算法,新生代里有 3 个分区:Eden、To Survivor、From Survivor,它们的默认占比是 8:1:1,它的执行流程如下:

  • 把 Eden + From Survivor 存活的对象放入 To Survivor 区;

  • 清空 Eden 和 From Survivor 分区;

  • From Survivor 和 To Survivor 分区交换,From Survivor 变 To Survivor,To Survivor 变 From Survivor。

每次在 From Survivor 到 To Survivor 移动时都存活的对象,年龄就 +1,当年龄到达 15(默认配置是 15)时,升级为老生代。大对象也会直接进入老生代。

老生代当空间占用到达某个值之后就会触发全局垃圾收回,一般使用标记整理的执行算法。以上这些循环往复就构成了整个分代垃圾回收的整体执行流程。

207. 说一下 JVM 调优的工具?

JDK 自带了很多监控工具,都位于 JDK 的 bin 目录下,其中最常用的是 jconsole 和 jvisualvm 这两款视图监控工具。

  • jconsole:用于对 JVM 中的内存、线程和类等进行监控;

  • jvisualvm:JDK 自带的全能分析工具,可以分析:内存快照、线程快照、程序死锁、监控内存的变化、gc 变化等。

208. 常用的 JVM 调优的参数都有哪些?

  • -Xms2g:初始化推大小为 2g;

  • -Xmx2g:堆最大内存为 2g;

  • -XX:NewRatio=4:设置年轻的和老年代的内存比例为 1:4;

  • -XX:SurvivorRatio=8:设置新生代 Eden 和 Survivor 比例为 8:2;

  • --XX:+UseParNewGC:指定使用 ParNew + Serial Old 垃圾回收器组合;

  • -XX:+UseParallelOldGC:指定使用 ParNew + ParNew Old 垃圾回收器组合;

  • -XX:+UseConcMarkSweepGC:指定使用 CMS + Serial Old 垃圾回收器组合;

  • -XX:+PrintGC:开启打印 gc 信息;

  • -XX:+PrintGCDetails:打印 gc 详细信息。

IDEA commands


Alt Enter show die Action
Ctrl Shift o load Maven file
F10 Consturctor
f11 Full screen mode
C-x, C-c close tab page
shift Alt up move line up 行上移 shift Alt down move line down 行下移



Ctrl + Folding/expand 展开代码 Ctrl - Folding/Collapse 折叠代码 Ctrl spc mark postion 设定开始mark的位置 Alt x open action 执行任何命令 Alt t open terminal 打开terminal Alt ; comment line 注释行(单行不必选中) Alt w cope 复制 Ctrl y paste 粘贴 Alt y paste from history 粘贴 Alt l reformat file 格式化文件格式(缩进) Alt Einfg Generate /New 生成/新建 Alt i go to Implement 去实现类 Alt f go to File 去文件 Alt c go to Class 去类 Alt s go to Symbol 去符号定义 Alt g go to line 去行 Alt . go to Declaration 去查看定义 Alt d database 打开数据库 Ctrl Alt m main menu 关闭/打开main menu Ctrl Alt l line number 行数 Ctrl Alt r run run, debug, test Ctrl Alt del close project 关闭项目 Ctrl Alt Spc extend Selection 扩展选取 Ctrl Alt u Undo 撤销 Ctrl Alt Enter external emacs emacs Ctrl Alt c new class 新建类 Ctrl Alt b Tool Window Bars 打开周围的功能 Ctrl Alt v introduce Variable 自动生成类型赋值 Ctrl Alt s replace 查找并替换


java in SRC

SRC can't load all package, so import java.io.* doesn't work. Muss ganz die Name nennen: import java.io.File; import java.io.FileReader


title: JS

#+STARTUP: overview

Array

push unshift pop shift


let arrayy = ["Apple", "Banane", "Orange"]
console.log("push Krisch");
arrayy.push("Krisch")
console.log(arrayy);
console.log("unshift Biren");
arrayy.unshift("Biren")
console.log(arrayy);
console.log("pop");
arrayy.pop();  
console.log(arrayy);
console.log("shift");
arrayy.shift();  
console.log(arrayy);  

push Krisch
[ 'Apple', 'Banane', 'Orange', 'Krisch' ]
unshift Biren
[ 'Biren', 'Apple', 'Banane', 'Orange', 'Krisch' ]
pop
[ 'Biren', 'Apple', 'Banane', 'Orange' ]
shift
[ 'Apple', 'Banane', 'Orange' ]

methods for Array


pop() push() shift() unshift() splice(0,1,2) slice(0,1) concat() sort(function(a,b)return(a-b)) reverse() map(value, index, array) filter(value, index, array) reduce(total, value, index, array) every(value, index, array) some(value, index, array) indexOf() find(value, index, array)

function mymap(value, index, array){
  return value*array[index]
}
let arr = [1,2,3,4,5];
console.log(arr.map(mymap));
function myreduce(total, value, index, array){
  return total+value*array[index]
}
let arr = [1,2,3,4,5];
console.log(arr.reduce(myreduce, 10));

set array 去重 求交

let arr = [1,2,3,4,5,6,7,4,5,6];
let arr2 = [2,4,6];
let result = [...new Set(arr)].filter(
  item => new Set(arr2).has(item)
);
console.log(result);

Class

ES5

class mit generate function

function Phone(brand, price){
    this.brand = brand;
    this.price = price;
}

Phone.prototype.call = function(){
    console.log("I want to make a phone");
}

let Huawei = new Phone("HuAwei", 5998);

console.log(Huawei)

ES6

class Phone{
    constructor(brand, price){
        this.brand = brand;
        this.price = price;
    }

    call(){
        console.log("I will make a call");
    }
}

let onePlus = new  Phone("1+", 2000);
console.log(onePlus);

setTimeout


setTimeout(  function(){console.log("1090kjk0")}    , 2000);
setTimeout(  ()=>{console.log("10900")}             , 2000);

setTimeout(  ()=>{      } , 2000);

no name function

(()=>{console.log("testtest") })();
(function(){console.log("testtest")})()

构造函数也是类

  function Person(name, age){
      this.name = name;
      this.age = age;
      this.sagenhallo = function(){
          console.log("hallo");
      }
    return {a:this.age};
  }

  let xiaoming =  Person("xiaoming", 20);
  console.log(xiaoming);
  console.log(xiaoming.name);
//  xiaoming.sagenhallo();



{ a: 20 }
undefined

let

不能重复赋值

let a = 1;
let b = [];
let c = "kdjfie";
console.log(c)
let a = 3;

有块级作用域

{
    let girls = "meimei";

    function fnnn(){
        console.log(girls);
    }

    fnnn();
}

console.log(girls);
meimei

没有变量提升

console.log(song)
let song = "kaka"

const

注意

初始一定要赋值 一般使用大写 不能修改 有块级作用域

对象和复合型的可以修改

const name = ["wangba", "wuqing", "tiankong"]
name.push("gousi")
console.log(name)

[ 'wangba', 'wuqing', 'tiankong', 'gousi' ]

数组和对象可以被解构的赋值

const F4 = ["zhangsan", "lisi", "wangwu", "zhaoliu"];
let [f1, f2, f3, f4] = F4
console.log(f2)

lisi
const zhao = {
    name: "benshan",
    age:"unkownen",
    xiaoping :function(){
        console.log("I K y");
    }
};
let {name, age, xiaoping} = zhao;
console.log(age);
console.log(xiaoping);
xiaoping();

unkownen
[Function: xiaoping]
I K y

模板字符串可以换行,拼接

´${}´ 可以拼接变量 可以换行

简化对象

let name = "sangguigu";
let change = function(){
    console.log("I can make it");
};

const school = {
    name,
    change,
    improve(){
        console.log("We can help you");
    }
};

console.log(school.name);
console.log(school.change);
school.change()
school.improve()

sangguigu
[Function: change]
I can make it
We can help you

箭头函数

静态的this, 当前作用域的this,call都不能改变 不能构造对象实例化 不能使用arguments

let qual = n => n*n;
let fn = (a,b) => { return a*b};
console.log(qual(3))
console.log(fn(2,5));
9
10

rest

ES5

function data(){
    console.log(arguments);
}
data("nihao", "niyehao");

[Arguments] { '0': 'nihao', '1': 'niyehao' }

ES6

function data(...args){
    console.log(args);
}
data(1,2,3,4);

[ 1, 2, 3, 4 ]
function data(a, b, ...args){
    console.log(a);
    console.log(b);
    console.log(args);
}
data(1,2,3,4,5,6);

1
2
[ 3, 4, 5, 6 ]

扩展运算符...

Beispiel 将内容转化为数组

const name = ["wangyi", "wanger","wangsan"];
let putname = function(){
    console.log(arguments);
};
putname(...name);

[Arguments] { '0': 'wangyi', '1': 'wanger', '2': 'wangsan' }

Anwendung

const kuaizi = ["王太利","肖扬"];
const fenghuang = ["冯坤", "来用"];
console.log(kuaizi.concat(fenghuang));
console.log([...kuaizi, ...fenghuang])

[ '王太利', '肖扬', '冯坤', '来用' ]
[ '王太利', '肖扬', '冯坤', '来用' ]

Symbol

唯一性, 不能运算, 用for表唯一

let s = Symbol();
let ss = Symbol("shanggui");
let sss = Symbol("shanggui");
console.log(ss === sss);

let ss1 = Symbol.for("shanggui");
let sss1 = Symbol.for("shanggui");
console.log(ss1 === sss1);

false
true

给对象添加属性和方法

let youxi = {
    name:"狼人杀",
    [Symbol("say")]: function(){
        console.log("发言");
    },
    [Symbol("nosay")]: function(){
        console.log("闭眼");
    }
};

console.log(youxi);

let addmethod = {
    up: Symbol(),
    down:Symbol()
};

youxi[addmethod.up] = function(){
    console.log("up");
};

youxi[addmethod.down] = function(){
    console.log("down");
};

console.log(youxi);
{
  name: '狼人杀',
  [Symbol(say)]: [Function: [say]],
  [Symbol(nosay)]: [Function: [nosay]]
}
{
  name: '狼人杀',
  [Symbol(say)]: [Function: [say]],
  [Symbol(nosay)]: [Function: [nosay]],
  [Symbol()]: [Function (anonymous)],
  [Symbol()]: [Function (anonymous)]
}

迭代器

const xiyou = ["唐僧", "孙悟空", "猪八戒", "沙僧"]
for (let v in xiyou){
    console.log(v);
}

for (let v of xiyou){
    console.log(v);
}

0
1
2
3
唐僧
孙悟空
猪八戒
沙僧
let cluster = {
    name:"tiankong",
    age: [1,2,3,5,7,9],
    [Symbol.iterator]() {
        let index = 0;
        let _that = this;
        return {
            next: function(){
                if (index < _that.age.length) {
                    const result = {value:_that.age[index], done:false };
                    index++;
                    return result;
                }else{
                    return {value:undefined, done:true};
                }
            }
        };
    }
}

for(let v of cluster){
    console.log(v);
}

1
2
3
5
7
9

生成器

function *gen(){
    console.log("1");
    yield "一";
    console.log("2");
    yield "二";
}

for (let v of gen()){
    console.log(v);
}
let iter = gen();


iter.next();
for (let v of iter){
    console.log(v);
}

1
一
2
二
1
2
二
function *gen(args){
    console.log(args);   // can only be passed once at first
    console.log("1");
    let mmm = yield "一"; // each step can be passed
    console.log(mmm);
    console.log("2");
    yield "二";
    console.log("3");
    yield "三";

}

let iter = gen("aaa");

iter.next();
iter.next("MMM")
iter.next();

aaa
1
MMM
2
3

type vaildation

basic

tpyeof: the rest ={.verbatim} : null, undefined 开始: let a = null; 说明a后来要被赋值为object 结束: a = null; 释放b的内存

var a;
console.log()
console.log(typeof(a))
console.log(typeof a)
console.log(typeof a==="undefined" )
console.log(a===undefined )

undefined
undefined
true
true

class

instanceof typeof 不能区分数组和函数和对象

  var bb = {
    bb1 : [1, "niaho", console.log],
    bb2 : function(){
      console.log("nidf");
    }
  }

console.log(bb instanceof Object);
console.log(bb.bb1 instanceof Array);
console.log(bb.bb1 instanceof Object);
console.log(bb.bb2 instanceof Function);
console.log(bb.bb2 instanceof Object);
console.log( typeof bb.bb1[2] === "function")
bb.bb1[2](4)

true
true
true
true
true
true
4

multi assigment

如果两个变量指向一个引用地址,修改其中一个,修改结果另一个可见 如果一个重新指向(例如某个函数赋值),另一个内容不变

call

对于obj没有test()方法, 临时调用 test.call(obj) ={.verbatim} obj.test() test.apply(obj) ={.verbatim} obj.test()

IIFE Immediately Invoked Function Expression

Beispiel

1: 不影响全局命名空间 2:可以暴露

(function (){
    let a = 34;
    console.log("kk!!!!");
    console.log(a*34);
})();

kk!!!!
1156

浏览器端列子

这里不能执行

(
    function(){
        let aa = 1;
        function test(){
            console.log(++aa);
        };
        window.$ = function(){
            return {
                test:test
            };
        };
    }
)();

$().test();



服务器端列子

(
    function(window){
        let aa = 1;
        function test(){
            console.log(++aa);
        };
        window.$ = function(){
            return {
                test:test
            };
        };
    }
)(this);

this.$().test();



2

this

任何函数本质都是通过对象来调用的, 如果没有指定调用者,那么就是window

括号

小括弧(IIFE)和中括弧(Beispiel untern)前面的语句后必须加分号, 否则分号全部可以省略

[1,2,3,4].forEach(function(a){console.log(a)})
;[1,2,3,4].forEach(a =>console.log(a))

1
2
3
4
1
2
3
4

callback

callback named function

 var test = function(msg, callback){
     setTimeout(function(){ console.log(msg);   }, 2000);
     //console.log(msg);
     callback(); 
 }
function  justcall(){
     console.log("juskjktcallkkjk to i ");
 }
var just = function(){
     console.log("juskjktcallkkjk to i ");
 }
 test("nisho 0p", justcall)
 test("nisho 0p", just)

callback no named function

  var test = function(msg , didi){
//      setTimeout( ()=>{   console.log(msg);   } , 2000);
      console.log(msg);
      didi(msg);
  }

  test("kdjfi", msg => {
      console.log(msg);
  });

no named function callback no named function

(
    (msg , didi) => {
        console.log(msg);
        //          setTimeout(  ()=>{    didi(msg);  } , 2000);  // can only be used in  function body
        didi(msg); 
    }
)
( "kdiikkjkjk",
  msg => {
      console.log(msg);
  }
)

promise

resolve and reject


resolve 触发 then 回调 reject 触发 catch 回调

let sentSuccess = false;
let p = new Promise(function(resolve, reject) {
  if(sentSuccess){
    resolve("Successed");
  } else {
    reject("Failed");
  }
});

p.then(function(message) {
  console.log(`${message} is coming`);
}).catch(function(message){
  console.log(`${message} is coming`);
})

Failed is coming

resolve and reject with recusive


then 执行后正常返回 resolved状态, 出错返回rejected 状态 catch 执行后正常返回 resolved状态, 出错返回rejected 状态

Promise.resolve().then( ()=> {
    console.log(1);
}).catch(()=> {
    console.log(2);
}).then(()=> {
    console.log(3);
});

1
3
Promise.resolve().then( ()=> {
    console.log(1);
    throw new Error ('Error');
}).catch(()=> {
    console.log(2);
}).then(()=> {
    console.log(3);
});

1
2
3
Promise.resolve().then( ()=> {
    console.log(1);
    throw new Error ('Error');
}).catch(()=> {
    console.log(2);
}).catch(()=> {
    console.log(3);
});

1
2
let sentSuccess = true;
let p = new Promise(function(resolve, reject) {
  if(sentSuccess){
    resolve("Successed");
  } else {
    reject("Failed");
  }
});

p.then(function(message) {
  console.log(`${message} is coming`);
  console.log(1);
  throw new Error ('Error');
}).catch(()=> {
  console.log(2);
}).catch(()=> {
  console.log(3);
}).catch(function(message){
  console.log(`${message} is coming`);
}).then(() => {
  console.log(4);  
});

Successed is coming
1
2
4

resolve and reject with recusive with return

  let sentSuccess = false;
  let p = new Promise(function(resolve, reject) {
    if(sentSuccess){
      resolve("Successed");
    } else {
      reject("Failed");
    }
  });

  p.then(function(message) {
    console.log(`${message} is coming`);
    return "niaho";
  }).then(function(massage) {
    console.log(massage)
  }).catch(function(message){
    console.log(`${message} is coming`);
    return "nibuaho";
  }).then(function(massage) {
    console.log(massage)
  })

* Closure
** conuter将函数作为另一个函数的返回值
#+begin_src js :results output :exports both
  function f1(){
      let a = 0;
      function f2(){
          a++;
          console.log(a);
      }
      return f2;
  }

  var f = f1();
  f()
  f()
  f();

1
2
3

将函数作为实参传给另一个函数调用

实际上,这和回调函数是一样的

function print(fn){
    let a = 200;
    fn();
}

let a = 100;
function fn(){
    console.log(a);
}
print(fn);

100

multi return

function myModule(){
    let msg = "My Massage";

    function doSomething(){
        console.log("do Something..."+msg);
    }
    function doOtherthing(){
        console.log("do Otherthing..." + msg);
    }

    return {
        Something:doSomething,
        Otherthing:doOtherthing
    };
}

let F = myModule();
F.Something()
F.Otherthing()

do Something...My Massage
do Otherthing...My Massage

Prototype

new note

每一个函数都有一个prototpye属性&,默认是个对象, 即原型对象 该prototype原型对象有constructor属性和_proto_属性 constructor指向函数对象(回去了) fun.prototype = &, &.constructor = fun

constructor

function Fun(){  }
var yuanxing = Fun.prototype
var yuanhanshu = yuanxing.constructor
console.log(yuanhanshu == Fun)
console.log(Fun.prototype.constructor == Fun)
true
true

prototype 显式原型 函数类 定义时被生成 添加方法给类的原型对象 还可以对原型对象添加自定义的属性和方法,让原型对象的函数的实列来使用

function Fun(){  }
Fun.prototype.test = function(){console.log("prototype for test")}
var fun = new Fun()
fun.test()
prototype for test

[[proto]{.underline}]{.underline} 隐式原型 实列 实列化时生成

类的显式原型等于实列的隐式原型

function Fun(){}
var fun = new Fun()
console.log(Fun.prototype)
console.log(fun.__proto__)
console.log(Fun.prototype == fun.__proto__)
{}
{}
true

[[proto]{.underline}]{.underline} 原型链* 如果为被复制,则默认为系统Object空对象

    function Fun(){}
    var fun = new Fun()

    function FFun (){}
    var ffun = new FFun()

  FFun.prototype.__proto__ = fun
//  ffun.__proto__.__proto__ = fun

    console.log(ffun.__proto__.__proto__)
Fun {}

alte note

对象的隐式原型([[proto]{.underline}]{.underline})等于对应的构造函数的显式原型(prototype)的值 [photolink]{.spurious-link target="~/Dropbox/subjects/foto/JS_Obj_Fuck_prototype.png"} 对象的属性组成: 1:本身的声明 2:_proto_隐式原型链属性 3:系统Object的原型对象,其_proto__ = null

function Fn (){
}
var fn = new Fn();

Fn.prototype.test = function(){
    console.log("from prototype");
}

fn.test();  // === fn.__proto__.test();
fn.__proto__.test();

from prototype
from prototype
console.log(Object.prototype instanceof Object)
console.log(Function.prototype instanceof Object)
console.log(Function.__proto__ === Function.prototype)
false
true
true
function A(){};
A.prototype.n = 1;
var b = new A();
A.prototype = {
    n:2,
    m:3
};
var c = new A();
console.log(b.n, b.m, c.n, c.m);
1 undefined 2 3
function F(){}

Object.prototype.a = function(){
    console.log("a")
}
Function.prototype.b = function(){
    console.log("b")
}
var f = new F();
f.a()
f.b()
F.a()
F.b()


event loop事件循环

  • browser interpreter
  • Call stack
  • Web API
  • Call query
  • event loop

async/await

::: center 用同步语法编写异步代码 :::

执行async函数, 返回的是Promise

如果没有Promise的调用,也会自动封装为Promise

async function fn1(){
    return 1000;
}
fn1().then(data => {
    console.log("data :", data);
});
data : 1000

如果有,则直接返回该Promise

async function fn1(){
    return Promise.resolve(200);
}
const res1 = fn1();
res1.then(data => {
    console.log("data :", data);
});
data : 200

await 相当于 Promise + then

await 后面跟数值也会自动封装

(async function (){
    const data = await 300;
    console.log(data);
})();
300

await 跟Promise

(async function (){
    const p1 = Promise.resolve(200);
    const data = await p1;
    console.log(data);
} )();
200

await跟async函数

async function fn1(){
    return 300;
}

(async function (){
    const data = await fn1();
    console.log(data);  // 此时await后面的命令相当与setTimeout的第二个参数,即新的异步分支
} )();
300

try catch 捕获异常,代替Promise+catch

(async function (){
    const p4 = Promise.reject('Error');
    try {
        const res = await p4;
        console.log(res); // reject for Promise + then, this will not be executed
    } catch (err) {
        console.log(err);
    } finally {
        console.log("It's done");
    }
})();
Error
It's done

包装长时耗的异步函数

function sendRequest(){
  return new Promise(function(resolve, reject) {
    setTimeout( function(){
      reject("Request reject");
    }, 2000);
  });
}

async function getUsername() {
  try {
    let username =  await sendRequest();
    console.log(username);
  } catch (err) {
    console.log(`Error: ${err}`);
  } finally {
    console.log("Gut");
  }
}

getUsername()

Error: Request reject
Gut

js in Dom

<li><a onclick="emacs()" href="#">Emacs</a></li>
<iframe src="emacs.html" id="emacs" class="hidden" ; style="position:fixed; top:50px; left:0; bottom:0; right:0; width:100%; height:100%; border:none; margin:0; padding:0; overflow:hidden; z-index:999999;" ></iframe>
document.querySelectorAll('iframe').forEach( item => item.setAttribute('class','hidden'))
document.getElementById("UniversalHashing").setAttribute('class','showing')

...rests

使用在一个表达式前,表示整个表达式的值, 例如整个数组或者对象

var test = {a:0, b:1, c:2}
var testall = {...test, d:5}
console.log(testall)

var parts = ['0', '1','2']
var alles = [...parts, '3']
console.log(alles)


{ a: 0, b: 1, c: 2, d: 5 }
[ '0', '1', '2', '3' ]

add function to window

with $ this example is special for now, virtual DOM

( function(window){
    let aa = 9;
    function test(){
        console.log(++aa);
    };
    window.$ = function(){
        return {
            test:test,
            aa:aa
        };
    };
}
)(this);

console.log(this);
console.log(this.$);
console.log(this.$());
console.log(this.$().aa);
this.$().test();
{ '$': [Function (anonymous)] }
[Function (anonymous)]
{ test: [Function: test], aa: 9 }
9
10

change this with call apply bind

call function

改变函数运行的this值,即指向, 并得到运行后的结果, 通过增加方法并事后删除的方式完成 let the this attribution of call function be banded with another instance, and calculate the result.

if the another instance is null or undefined, in ES11, globalThis will replace this instance with window

  function call(Fn, obj, ...args){
      if (obj == undefined || obj == null) {
          obj = globalThis;
      }
      obj.temp = Fn;
      var resulte = obj.temp(...args);
      delete  obj.temp;
      return resulte;
  }

  function add(a, b){
      console.log(this);
      return a+b+this.c;
  }
  let obj ={
      c:2
  };

  console.log(call(add, obj, 10, 10));
//将add的this值等于obj的this

  //  window.c = 10;
globalThis.c = 2;
console.log(call(add, null, 10, 10));

{ c: 2, temp: [Function: add] }
22
<ref *1> Object [global] {
  global: [Circular *1],
  clearInterval: [Function: clearInterval],
  clearTimeout: [Function: clearTimeout],
  setInterval: [Function: setInterval],
  setTimeout: [Function: setTimeout] {
    [Symbol(nodejs.util.promisify.custom)]: [Function (anonymous)]
  },
  queueMicrotask: [Function: queueMicrotask],
  clearImmediate: [Function: clearImmediate],
  setImmediate: [Function: setImmediate] {
    [Symbol(nodejs.util.promisify.custom)]: [Function (anonymous)]
  },
  a: 3,
  c: 2,
  temp: [Function: add]
}
22

apply function

唯一和call不同是: apply的第三个开始的数据参数是一个整体,比如数组

  function apply(Fn, obj, args){
      if (obj == undefined || obj == null) {
          obj = globalThis;
      }
      obj.temp = Fn;
      var resulte = obj.temp( ...args);
      delete  obj.temp;
      return resulte;
  }
  function add(a, b){
      console.log(this);
      return a+b+this.c;
  }
  let obj ={
      c:2
  };
  global.a = 3;
  console.log(apply(add, obj, [2,4]));
//将add的this值等于obj的this
  //  window.c = 10;
globalThis.c = 2;
console.log(apply(add, null, [2, 4]));
{ c: 2, temp: [Function: add] }
8
<ref *1> Object [global] {
  global: [Circular *1],
  clearInterval: [Function: clearInterval],
  clearTimeout: [Function: clearTimeout],
  setInterval: [Function: setInterval],
  setTimeout: [Function: setTimeout] {
    [Symbol(nodejs.util.promisify.custom)]: [Function (anonymous)]
  },
  queueMicrotask: [Function: queueMicrotask],
  clearImmediate: [Function: clearImmediate],
  setImmediate: [Function: setImmediate] {
    [Symbol(nodejs.util.promisify.custom)]: [Function (anonymous)]
  },
  a: 3,
  c: 2,
  temp: [Function: add]
}
8

bind function

do the same thing as call, but do not execute, return a function which can be executed. 注意传值

function call(Fn, obj, ...args){
    if (obj == undefined || obj == null) {
        obj = globalThis;
    }
    obj.temp = Fn;
    var resulte = obj.temp(...args);
    delete obj.temp;
    return resulte;
};

function bind(Fn, obj, ...args){
    return function(...arg){
        return call(Fn, obj, ...args, ...arg);
    };

}

globalThis.c = 2;
let obj = {c:2};

function add(a, b){
    return a+b+this.c;
}
let fff =bind(add, obj, 2);
console.log(fff(1));

5

Jest

init

  • init

npx jest --init npx jest --coverage / npm run coverage

  • autodetect

packages.json->"scripts": "test":"jest", ---->>>> "test":"jest --watchall",

  • babel

npm install @bable/core@7.4.5 @bable/preset-env@7.4.5 -D touch .babelrc

  • model

a model o model f model p model

runing node npm js fetch async await

  • npm init

  • "type": "module", >> package.json

  • npm install node-fetch

    import fetch from 'node-fetch';
    
    fetch("https://pokeapi.co/api/v2/pokemon/")
      .then((res) => res.json())
      .then((data) => console.log(data)); 
    
  • node index.js

jest test npm js fetch async await

  • npm init -y

  • "type": "module", >> package.json

  • npm install node-fetch

    import fetch from 'node-fetch';
    
    const getPokemonList = async() => {
      const listRep = await fetch("https://pokeapi.co/api/v2/pokemon/");
      return await listRep.json();
    };
    
    const getPokemon = async(url) => {
      const dataResp = await fetch(url);
      return await dataResp.json();
    };
    
    
    
    function sum(a, b) {
      return a + b;
    }
    module.exports = {
      sum,
      getPokemon,
      getPokemonList
    };
    
  • Here, because jest are default use CommonJS, so please PLEASE revoke your node-fetch to version 2. Because node-fetch after version 3, it will be convert to ES6.

  • npm remove node-fetch

  • npm install node-fetch@2.6.2

    const {sum, getPokemon, getPokemonList } = require('./index');
    
    test("testSum", () => {
      expect( sum(1, 2) ).toBe(3);
    });
    
    test("testDict", () => {
      const data = {one: 1};
      data["two"] = 2;
      expect( data ).toEqual({one:1, two:2});
    });
    
    
    test("testgetPokemonList", async () => {
      const pokemonList = await getPokemonList();
      const firstPokemon = await getPokemon(pokemonList.results[0].url);
      expect(firstPokemon.name).toBe("bulbasaur");
    });
    
    
    
  • but the index.js is using ES6 to import fetch-node, even use module.exports(for CommonJS) and require, but import is still complaining.

  • npm i -s @bable/preset-env

  • npm i -s babel-jest

  • touch .babelrc

    {
      "presets": ["@babel/preset-env"]
    }
    
  • npm run test should now work

yarn ts fetch async await

  • cd asyncts

  • yarn init -y

  • yarn add typescript ts-node @types/node-fetch@2.6.2

  • yarn add node-fetch@2.6.2

  • npx tsc --init

    import fetch from "node-fetch"
    fetch("https://pokeapi.co/api/v2/pokemon/")
      .then((res) => res.json())
      .then((data) => console.log(data)); 
    
    
  • ts-node index.ts

    node-fetch convert every thing into EMS moduld after version 3.0 if you meet some error, please use the last version 2

  • yarn add @supercharge/promise-pool

  • yarn add ts-jest jest @types/jest -D

  • npx ts-jest config:init

  • yarn test

  • seeing the demo ~/Dropbox/cs/asyncTSPromisejest


title: Go

#+STARTUP: overview

Go Features

Note

Array

  • Array & Slice: Array must with specialized length for [x]
  • function:
    • must given specialized arguments(if point) when execution
  • method:
    • Must have a receiver
    • if receiver is pointer of instance, the value of instance can be modified
    • for execution: the instance of receiver can be pointer or not, will automatically convered
    • if receiver is not a pointer, the receiver can still be a pointer

interface

  • def interface with its contains
  • def receiver
  • receiver implementing the contains with methods(just like method above)
  • instancing of interface
  • instancing of receiver
  • passing receiver to interface(if the implementation is kind of pointer for receiver, here also pass pointer)
  • executing methods of interface

Slice

As you've noticed, when you slice from the end, it's the length that shrinks. The pointer to the first element and the capacity remain unchanged.

When you slice from the beginning of the slice, though, what happens instead is the pointer to the first element is changed to be a pointer to the nth element that you're slicing from (i.e. sl = arr[2:] means to set the pointer to point to &arr[2]). Because the head of the slice has moved forward 2, in this case, the length and capacity have to decrease by 2.

Generics

package main
import "fmt"
func Sum[V int64 | float64](m ...V) V {
        var s V
        for _,v := range m {
                s += v
        }
        return s
}
func main() {
        fmt.Println(Sum([]int64{1,2,3,4,5}...))
        fmt.Println(Sum(int64(1),int64(2),int64(3),int64(4)))
        fmt.Println(Sum(1.1, 2.2, 3.3, 4.4))
}  
package main
import (
        "fmt"
        "golang.org/x/exp/constraints"
)
func Sum[V constraints.Float | constraints.Integer](m ...V) V {
        var s V
        for _,v := range m {
                s += v
        }
        return s
}
func main() {
        fmt.Println(Sum([]int64{1,2,3,4,5}...))
        fmt.Println(Sum(1,2,3,4))
        fmt.Println(Sum(1.1, 2.2, 3.3, 4.4))
        fmt.Println(Sum(uint32(2), uint32(4)))
}  
cd babel
go mod init go-generics-constraints
go mod tidy
go build go_generics_constraints.go
rm main.go
rm go.mod
rm go.sum
./go_generics_constraints
15
10
11
6

Strings

package main
import (
        "fmt"
        "strings"
)
func main() {
        cut := func(sep string) {
                s:= "hello|world"
                before, after, found := strings.Cut(s, sep)
                fmt.Printf("Cut(%q, %q): %q, %q, %v\n", s, sep, before, after, found)
        }
        cut("|")
        cut("hello")
        cut("nothing")
}
Cut("hello|world", "|"): "hello", "world", true
Cut("hello|world", "hello"): "", "|world", true
Cut("hello|world", "nothing"): "hello|world", "", false

Array

package main
import (
        "fmt"
)
func test(array []int64) {
        for i:= 0; i< 3; i++{
                array[i] = 10
        }
}

func main() {
        start := make([]int64, 3)
        test(start)
        fmt.Println(start)
}



[10 10 10]

Map

three way to create a map

package main
import (
        "fmt"
)
func main() {
        myMap1 := make(map[string]string, 10)
        fmt.Println(myMap1)
        myMap1["one"] = "python"
        fmt.Println(myMap1)
        myMap2 := make(map[string]string)
        myMap2["one"] = "python"
        fmt.Println(myMap2)          
        myMap3 := map[string]string{
                "one": "python",
        }
        fmt.Println(myMap3)
}
map[]
map[one:python]
map[one:python]
map[one:python]

Methode

function(copy or pointer) methode(copy or pointer)

interface

package main
import (
        "fmt"
)
type AnimalIF interface{
        Sleep()
        GetColor() string
        GetType() string
}

type Cat struct{
        color string
}

func (this *Cat) Sleep(){
        fmt.Println("Cat is sleeping")
}
func (this *Cat) GetColor() string {
        return this.color
}
func (this *Cat) GetType() string {
        return "Cat"
}

type Dog struct{
        color string
}

func (this *Dog) Sleep(){
        fmt.Println("Dog is sleeping")
}
func (this *Dog) GetColor() string {
        return this.color
}
func (this *Dog) GetType() string {
        return "Dog"
}
func ShowInfo(animal AnimalIF){
        animal.Sleep()
        fmt.Println("color = ", animal.GetColor())
        fmt.Println("type = ", animal.GetType())
}

func main() {
        cat := Cat{"Green"}
        dog := Dog{"Yellow"}
        ShowInfo(&cat)
        ShowInfo(&dog)
}
Cat is sleeping
color =  Green
type =  Cat
Dog is sleeping
color =  Yellow
type =  Dog

interface {} assert: arg.(string), if arg is not {}, it will be forced to convert to string can refer to every kind of value

polymorphism

OpenFile already implemented Wirter and Reader

package main

import (
    "fmt"
    "io"
    "os"
)

func main() {
    tty, err := os.OpenFile("/dev/tty", os.O_RDWR, 0)
    if err != nil {
        fmt.Println("Open file with error", err)
        return
    }
    var r io.Reader
    r = tty
    var w io.Writer
    w = r.(io.Writer)
    w.Write([]byte("HELLO from meb\n"))
}


Open file with error open /dev/tty: no such device or address

reflect

package main

import (
        "fmt"
        "reflect"
)

func reflectNum(arg interface{}){
        fmt.Println("type: ", reflect.TypeOf(arg))
        fmt.Println("value: ", reflect.ValueOf(arg))
}

func main(){
        var num float64 = 3.1415926
        reflectNum(num)
}

type:  float64
value:  3.1415926
package main
import (
        "fmt"
        "reflect"
)

type User struct {
        Id int
        Name string
        Age int
}

func (this User) Call(){
        fmt.Println("user is calling")
        fmt.Printf("%v\n", this)
}

func (this User) End_Call(id int){
        fmt.Println(id)
        fmt.Printf("%v\n", this)
}

func main(){
        user := User{10, "Alice", 23}
        reflectExample(user)
}

func reflectExample(input interface{}){
        //get tpye
        inputType := reflect.TypeOf(input)
        fmt.Println("input Type is :", inputType.Name())


        //get value
        inputValue := reflect.ValueOf(input)
        fmt.Println("value Type is :", inputValue)


        //get fields in details
        for i := 0; i< inputType.NumField(); i++ {
                field := inputType.Field(i)
                value := inputValue.Field(i).Interface()
                fmt.Printf("%s: %v = %v\n",field.Name, field.Type, value)
        }

        //get methods in details
        for i := 0; i< inputType.NumMethod(); i++ {
                method := inputType.Method(i)
                fmt.Printf("%s: %v\n", method.Name, method.Type)
        }
}
input Type is : User
value Type is : {10 Alice 23}
Id: int = 10
Name: string = Alice
Age: int = 23
Call: func(main.User)
End_Call: func(main.User, int)

time

package main
import (
    "fmt"
    "time"
)
func test() {
    start := time.Now()
    sum := 0
    for i := 0; i < 100000; i++ {
        sum++
    }
    elapsed := time.Since(start)
    fmt.Println("该函数执行完成耗时:", elapsed)
}

func main() {
    test()
}

该函数执行完成耗时: 33.536µs

sync

package main

import "fmt"

func produce(c chan<- int) {
    for i := 0; i < 10; i++ {
        fmt.Printf(" Produced : %d\n", i)
        c <- i // synchronization
    }
}

func consume(c <-chan int) {
    for true {
        i := <-c // synchronization
        fmt.Printf(" Consumed : %d\n", i)
    }
}

func main() {
    c := make(chan int)
    go consume(c)
    produce(c)
}
Produced : 0
 Consumed : 0
 Produced : 1
 Produced : 2
 Consumed : 1
 Consumed : 2
 Produced : 3
 Produced : 4
 Consumed : 3
 Consumed : 4
 Produced : 5
 Produced : 6
 Consumed : 5
 Consumed : 6
 Produced : 7
 Produced : 8
 Consumed : 7
 Consumed : 8
 Produced : 9
package main
import (
    "fmt"
    "time"
    "sync"
)
func main() {
    var wg sync.WaitGroup
    wg.Add(1)

    go func(){
        count("Sleep")
        wg.Done()
    }()
    wg.Wait()
}

func count(thing string) {
    for i := 1; i <= 5; i++ {
        fmt.Println(i, thing)
        time.Sleep(time.Millisecond*500)
    }

}
1 Sleep
2 Sleep
3 Sleep
4 Sleep
5 Sleep

go

package main
import (
    "fmt"
    "time"
)
func main() {
    var times int
    go func() {
        for {
        }
    }()
    go func() {
        for {
        }
    }()
    go func() {
        for {
        }
    }()
    go func() {
        for {
        }
    }()
    for times = 0; times <= 10; times++ {
        fmt.Println("tick", times)
        time.Sleep(time.Second)
    }
}

tick 0
tick 1
tick 2
tick 3
tick 4
tick 5
tick 6
tick 7
tick 8
tick 9
tick 10

chan

example

package main
import "fmt"
func main() {
    // 创建一个整型带两个缓冲的通道
    ch := make(chan int, 2)

    // 给通道放入两个数据
    ch <- 0
    ch <- 1

    // 关闭缓冲
    close(ch)
    // 遍历缓冲所有数据, 且多遍历1个
    for i := 0; i < cap(ch)+1; i++ {

        // 从通道中取出数据
        v, ok := <-ch

        // 打印取出数据的状态
        fmt.Println(v, ok)
    }
}
#+RESULTS:

dead lock unbuffer channel

package main
import "fmt"
func main() {
    // 创建一个整型带两个缓冲的通道
    ch := make(chan int)

    // 给通道放入两个数据
    ch <- 0
    id := <- ch
    fmt.Println(id)

    close(ch)
}

*but can be saved with goroutine*

package main
import "fmt"
func main() {
    ch := make(chan int)
    go func(){
      ch <- 0
    }()
    id := <- ch
    fmt.Println(id)
    close(ch)
}
0

deal lock after buffer channel is full

buffer can be filled

package main
import "fmt"
func main() {
    ch := make(chan int, 2)

    ch <- 0
    ch <- 1
    id := <- ch
    fmt.Println(id)

    close(ch)
}
0

but can not be exceeded

package main
import "fmt"
func main() {
    ch := make(chan int, 2)

    ch <- 0
    ch <- 1
    ch <- 2
    id := <- ch
    fmt.Println(id)

    close(ch)
}
0

context

package main

import (
    "fmt"
    "context"
    "time"
)

func enrichContext(ctx context.Context) context.Context {
    return context.WithValue(ctx, "request-id", "11212")

}

func doSomething(ctx context.Context){
    rID := ctx.Value("request-id")
    fmt.Println(rID)
    for {
        select {
        case <-ctx.Done():
            fmt.Println("times out")
            return
        default:
            fmt.Println("doing something cool")
        }
        time.Sleep(500*time.Millisecond)
    }
}


func main (){
    fmt.Println("Go Context example")
    ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
    defer cancel()
    fmt.Println(ctx.Err())
    ctx = enrichContext(ctx)
    go doSomething(ctx)
    select {
    case <- ctx.Done():
        fmt.Println("Oh, no, Time is execeed the deadline")
        fmt.Println(ctx.Err())
    }
    time.Sleep(2*time.Second)
}
Go Context example
<nil>
11212
doing something cool
doing something cool
doing something cool
doing something cool
Oh, no, Time is execeed the deadline
context deadline exceeded
times out
package main

import (
    "context"
    "fmt"
    "log"
    "time"
)

func main() {
    start := time.Now
    ctx := context.Background()
    userId := 10
    val, err := fetchUserData(ctx, userId)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println("result : ", val)
    fmt.Println("took ", time.Since(start()))
}

type Response struct {
    value int
    err   error
}

func fetchUserData(ctx context.Context, userid int) (int, error) {
    ctx, cancel := context.WithTimeout(ctx, time.Millisecond*200)
    defer cancel()

    respch := make(chan Response)

    go func() {
        val, err := fetchThirdPartyStuffWhichCanbeSlow()
        respch <- Response{
            value: val,
            err:   err,
        }
    }()

    for {
        select {
        case <-ctx.Done():
            return 0, fmt.Errorf("Fetch data is time out")
        case resp := <-respch:
            return resp.value, resp.err
        }
    }
}

func fetchThirdPartyStuffWhichCanbeSlow() (int, error) {
    time.Sleep(time.Millisecond * 150)
    return 666, nil
}

gonum

Test example

package main

import (
        "fmt"

        "gonum.org/v1/gonum/blas/blas64"
        "gonum.org/v1/gonum/mat"
)

func main() {
        r := row{1, 2, 3, 4}
        c := column{1, 2, 3}

        var m mat.Dense
        m.Mul(c, r)

        fmt.Println(mat.Formatted(&m))
        n := c.RawVector().N
        inc := c.RawVector().Inc
        d := c.RawVector().Data
        fmt.Println(n)
        fmt.Println(inc)
        fmt.Println(d)

        u := mat.NewVecDense(3, []float64{1, 2, 3})
        v := mat.NewVecDense(3, []float64{4, 5, 6})
        fmt.Println("u :", u)
        fmt.Println("v :", v)

}

// row is a user-defined row vector.
type row []float64

// Dims, At and T minimally satisfy the mat.Matrix interface.
func (v row) Dims() (r, c int)    { return 1, len(v) }
func (v row) At(_, j int) float64 { return v[j] }
func (v row) T() mat.Matrix       { return column(v) }

// RawVector allows fast path computation with the vector.
func (v row) RawVector() blas64.Vector {
        return blas64.Vector{N: len(v), Data: v, Inc: 1}
}

// column is a user-defined column vector.
type column []float64

// Dims, At and T minimally satisfy the mat.Matrix interface.
func (v column) Dims() (r, c int)    { return len(v), 1 }
func (v column) At(i, _ int) float64 { return v[i] }
func (v column) T() mat.Matrix       { return row(v) }

// RawVector allows fast path computation with the vector.
func (v column) RawVector() blas64.Vector {
        return blas64.Vector{N: len(v), Data: v, Inc: 1}
}

NewDense

package main

import (
        "fmt"
        "gonum.org/v1/gonum/mat"
)

func main() {
        zeros := mat.NewDense(3,5,nil)
        fmt.Println(zeros)
}

make

package main

import (
        "fmt"
        "math/rand"
        "gonum.org/v1/gonum/mat"
)

func main() {
        data := make([]float64, 36)
        for i := range data {
                data[i] = rand.NormFloat64()
        }
        a := mat.NewDense(6, 6, data)
        zeros := mat.NewDense(3,5,nil)
        // fmt.Println(mat.Formatted(zeros, mat.Prefix(""), mat.Squeeze()))
        // fmt.Println(mat.Formatted(a, mat.Prefix(""), mat.Squeeze()))
        eq := mat.Equal(a, zeros)
        fmt.Println(eq)

}

gonum execute

cd babel
go mod init babel-go
go mod tidy
go build main.go
rm main.go
rm go.mod
rm go.sum
./main
false

PatternDesign

Observer

package main

import (
        "fmt"
        "sync"
        "time"
)

type (
        eventObserver struct {
                id   int
                time time.Time
        }
        eventSubject struct {
                observers sync.Map
        }
        Event struct {
                data int
        }
        Observer interface {
                NotifyCallback(Event)
        }
        Subject interface {
                AddListener(Observer)
                RemoveListener(Observer)
                Notify(Event)
        }
)

// NotifyCallback ...
func (e *eventObserver) NotifyCallback(event Event) {
        fmt.Printf("Observer: %d Recieved: %d after %v\n", e.id, event.data, time.Since(e.time))
}

// AddListener ...
func (s *eventSubject) AddListener(obs Observer) {
        s.observers.Store(obs, struct{}{})
}

// RemoveListener ...
func (s *eventSubject) RemoveListener(obs Observer) {
        s.observers.Delete(obs)
}

// Notify  ...
func (s *eventSubject) Notify(event Event) {
        s.observers.Range(func(key interface{}, value interface{}) bool {
                fmt.Printf("%T", key)
                if key == nil || value == nil {
                        return false
                }
                key.(Observer).NotifyCallback(event)
                return true
        })
}

func fib(n int) chan int {
        out := make(chan int)
        go // name ...
        func() {
                defer close(out)
                for i, j := 0, 1; i < n; i, j = i+j, i {
                        out <- i
                }
        }()
        return out
}

func main() {
        n := eventSubject{
                observers: sync.Map{},
        }
        var obs1 = eventObserver{id: 1, time: time.Now()}
        var obs2 = eventObserver{id: 2, time: time.Now()}

        n.AddListener(&obs1)
        n.AddListener(&obs2)
        n.AddListener(&eventObserver{id: 3, time: time.Now()})

        go func() {
                select {
                case <-time.After(time.Millisecond):
                        n.RemoveListener(&obs2)
                }
        }()

        for x := range fib(1000000000000000000) {
                n.Notify(Event{data: x})
        }
}

Factory

package main

import (
        "fmt"
        "reflect"
)

type (
        mongoDB struct {
                database map[string]string
        }
        sqlite struct {
                database map[string]string
        }
        Database interface {
                GetData(string) string
                PutData(string, string)
        }
        file struct {
                name    string
                content string
        }
        ntfs struct {
                files map[string]file
        }
        ext4 struct {
                files map[string]file
        }
        FileSystem interface {
                CreateFile(string)
                FindFile(string) file
        }

        Factory func(string) interface{}
)

func (mdb mongoDB) GetData(query string) string {
        if _, ok := mdb.database[query]; !ok {
                return ""
        }
        fmt.Println("MongoDB")
        return mdb.database[query]
}

func (mdb mongoDB) PutData(query string, data string) {
        mdb.database[query] = data
}

func (sql sqlite) GetData(query string) string {
        if _, ok := sql.database[query]; !ok {
                return ""
        }
        fmt.Println("Sqlite")
        return sql.database[query]
}

func (sql sqlite) PutData(query string, data string) {
        sql.database[query] = data
}

func (ntfs ntfs) CreateFile(path string) {
        file := file{content: "NTFS file", name: path}
        ntfs.files[path] = file
        fmt.Println("NTFS")
}

func (ext ext4) CreateFile(path string) {
        file := file{content: "EXT4 file", name: path}
        ext.files[path] = file
        fmt.Println("EXT4")
}

func (ntfs ntfs) FindFile(path string) file {
        if _, ok := ntfs.files[path]; !ok {
                return file{}
        }
        return ntfs.files[path]
}

func (ext ext4) FindFile(path string) file {
        if _, ok := ext.files[path]; !ok {
                return file{}
        }
        return ext.files[path]
}

// DatabaseFactory ...
func DatabaseFactory(env string) interface{} {
        switch env {
        case "production":
                return mongoDB{
                        database: make(map[string]string),
                }
        case "development":
                return sqlite{
                        database: make(map[string]string),
                }
        default:
                return nil
        }
}

func FilesystemFactory(env string) interface{} {
        switch env {
        case "production":
                return ntfs{
                        files: make(map[string]file),
                }
        case "development":
                return ext4{
                        files: make(map[string]file),
                }
        default:
                return nil
        }
}

// AbstractFactoryy ...
func AbstractFactory(fact string) func(string) interface{} {
        switch fact {
        case "database":
                return DatabaseFactory
        case "filesystem":
                return FilesystemFactory
        default:
                return nil
        }
}

func SetupConstructors(env string) (Database, FileSystem) {
        fs := AbstractFactory("filesystem")
        db := AbstractFactory("database")
        return db(env).(Database), fs(env).(FileSystem)

}

func main() {
        env1 := "production"
        env2 := "development"

        // db1 := DatabaseFactory(env1)
        // db2 := DatabaseFactory(env2)

        db1, fs1 := SetupConstructors(env1)
        db2, fs2 := SetupConstructors(env2)

        db1.PutData("test", "for test")
        fmt.Println(db1.GetData("test"))
        db2.PutData("test2", "for test2")
        fmt.Println(db2.GetData("test2"))

        fs1.CreateFile("../example/fts.txt")
        fmt.Println(fs1.FindFile("../example/fts.txt"))

        fs2.CreateFile("../example/et4.txt")
        fmt.Println(fs2.FindFile("../example/et4.txt"))

        fmt.Println(reflect.TypeOf(db1).Name())
        fmt.Println(reflect.TypeOf(&db1).Elem())
        fmt.Println(reflect.TypeOf(db2).Name())
        fmt.Println(reflect.TypeOf(&db2).Elem())

        fmt.Println(reflect.TypeOf(fs1).Name())
        fmt.Println(reflect.TypeOf(&fs1).Elem())
        fmt.Println(reflect.TypeOf(fs2).Name())
        fmt.Println(reflect.TypeOf(&fs2).Elem())
}

MongoDB
for test
Sqlite
for test2
NTFS
{../example/fts.txt NTFS file}
EXT4
{../example/et4.txt EXT4 file}
mongoDB
main.Database
sqlite
main.Database
ntfs
main.FileSystem
ext4
main.FileSystem

Decorator

package main

import (
        "fmt"
        "log"
        "math"
        "os"
        "sync"
        "time"
)

func Pi(n int) float64 {
        ch := make(chan float64)
        for k := 0; k <= n; k++ {
                go func(ch chan float64, k float64) {
                        ch <- 4 * math.Pow(-1, k) / (2*k + 1)
                }(ch, float64(k))
        }
        result := 0.0
        for k := 0; k <= n; k++ {
                result += <-ch
        }
        return result
}

type piFunc func(int) float64

func wraplogger(fun piFunc, logger *log.Logger) piFunc {
        return func(n int) float64 {
                fn := func(n int) (result float64) {
                        defer func(t time.Time) {
                                logger.Printf("took=%v, v=%v, result=%v", time.Since(t), n, result)
                        }(time.Now())
                        return fun(n)
                }
                return fn(n)
        }
}

func wrapcache(fun piFunc, cache *sync.Map) piFunc {
        return func(n int) float64 {
                fn := func(n int) float64 {
                        key := fmt.Sprintf("n=%d", n)
                        val, ok := cache.Load(key)
                        if ok {
                                return val.(float64)
                        }
                        result := fun(n)
                        cache.Store(key, result)
                        return result
                }
                return fn(n)
        }
}

func divide(n int) float64 {
        return float64(n / 2)
}

func main() {
        // 01
        // fmt.Println(Pi(1000))
        // fmt.Println(Pi(50000))
        // 02
        //f := wraplogger(Pi, log.New(os.Stdout, "test", 1))
        // f(10000)
        //03
        f := wrapcache(Pi, &sync.Map{})
        g := wraplogger(f, log.New(os.Stdout, "test", 1))
        g(100000)
        g(200000)
        g(500000)
        g(500000)
        // 04
        f = wrapcache(divide, &sync.Map{})
        g = wraplogger(f, log.New(os.Stdout, "divide", 1))
        g(100000)
        g(200000)
        g(500000)
        g(500000)
}


test2022/07/12 took=197.241951ms, v=100000, result=3.1416026534897195
test2022/07/12 took=326.435601ms, v=200000, result=3.1415976535647596
test2022/07/12 took=678.005443ms, v=500000, result=3.1415946535856927
test2022/07/12 took=2.673µs, v=500000, result=3.1415946535856927
divide2022/07/12 took=15.404µs, v=100000, result=50000
divide2022/07/12 took=3.475µs, v=200000, result=100000
divide2022/07/12 took=1.724µs, v=500000, result=250000
divide2022/07/12 took=922ns, v=500000, result=250000

单例模式

package main

import (
        "fmt"
)

type User struct {
        Name       string
        Occupation string
}


type Moli interface {
        Changename()
        ChangeOccupation()
}

func  CreateUser() (Moli,  *User){
        var moli Moli
        u := new(User)
        moli = u
        return moli, u
}

func (u *User) Changename (){
        u.Name = "Joke"
}


func (u *User) ChangeOccupation (){
        u.Occupation = "driver"
}


func changeName(u User) {
        u.Name = "Newi"
}


func changeOccupation(u User) {
        u.Occupation = "driver"
}

func main() {
        M, user := CreateUser()
        fmt.Println("should be empty", user)

        user.Name = "kji"
        fmt.Println("Directly can change the name", *user)

        user.Occupation = "Nothing"
        fmt.Println("Directly can change the occupation", *user)

        changeName(*user)
        fmt.Println("In function, indieictly can not be changed", *user)

        changeOccupation (*user)
        fmt.Println("In function, idieictly can not be changed", *user)

        M.Changename()
        fmt.Println("In methode, indieictly can be changed its name", *user)

        M.ChangeOccupation()
        fmt.Println("In methode,  indieictly can be changed its occupation", *user)

}

should be empty &{ }
Directly can change the name {kji }
Directly can change the occupation {kji Nothing}
In function, indieictly can not be changed {kji Nothing}
In function, idieictly can not be changed {kji Nothing}
In methode, indieictly can be changed its name {Joke Nothing}
In methode,  indieictly can be changed its occupation {Joke driver}

Architecture

package

each folder can only has one named package, but it can be shared for many files, also for the test file

module

it is the same designed as project, but only without main function and main package. it can be used by local package, module or project, but has to be replaced

go mod edit -replace modulename=folder  
  • modul name is defined in the go.mod file, and also at last one package should named as it
  • floder can be relative path, or absolute path in the reference package, module or project.
  • can be called from gore, but first :import

project

  • the same with module, with main package and main func, can be call as go run xxx.go
  • can not be called from gore for now (29.07.2022)

here is also1 here is also2 here is also3 here is also4

pprof, allow cpu and mem profile

  import (
        "os"
        "time"

        "github.com/pkg/profile"
        "runtime/pprof"
)

  cpuFile, _ := os.Create("cpu.pprof")
  pprof.StartCPUProfile(cpuFile)
  defer pprof.StopCPUProfile()

  defer profile.Start(profile.MemProfile, profile.ProfilePath(".")).Stop()


title: RUST

#+startup: content

所有权

fn main() {
    let s1 = String::from("hello");
    let s2 = s1;

    println!("{}, world!", s2);
    // println!("{}, world!", s1);  

}

fn main() {
    let s = String::from("hello world");

    let word = first_word(s);

    //      s.clear(); // error!

    println!("the first word is: {}", word);
}
fn first_word(s: String) -> String {
    s
}


fn main() {
    #[derive(Debug)]
    struct User {
        active: bool,
        username: String,
        email: String,
        sign_in_count: u64,
    }

    let user1 = User {
        email: String::from("someone@example.com"),
        username: String::from("someusername123"),
        active: true,
        sign_in_count: 1,
    };
    // let user2 = User {
    //     email: String::from("another@example.com"),
    //     ..user1
    // };

    let user2 = User {
        active: user1.active,
        username: String::from("uset2"),
        email: String::from("another@example.com"),
        sign_in_count: user1.sign_in_count,
    };

    println!("{}", user1.email);
    // 下面这行会报错
    println!("{:?}", user2)

}



  • HITS: no matter with ..user1 or xxx: user1.xxx to create new user with old user, if only fundemantal elements have been copy, the old user can still be available, and the other non-fundemantal attributes also . Otherwise the old user instance and also the non-fundemantal attributes are both not available.

test

fn main() {
    let greetings = ["Hello", "Hola", "Bonjour",
                     "Ciao", "こんにちは", "안녕하세요",
                     "Cześć", "Olá", "Здравствуйте",
                     "chào bạn", "您好"];

    for (num, greeting) in greetings.iter().enumerate() {
        print!("{} : ", greeting);
        match num {
            0 =>  println!("This code is editable and runnable!"),
            1 =>  println!("Este código es editable y ejecutable!"),
            2 =>  println!("Ce code est modifiable et exécutable!"),
            3 =>  println!("Questo codice è modificabile ed eseguibile!"),
            4 =>  println!("このコードは編集して実行出来ます!"),
            5 =>  println!("여기에서 코드를 수정하고 실행할 수 있습니다!"),
            6 =>  println!("Ten kod można edytować oraz uruchomić!"),
            7 =>  println!("Esse código é editável e executável!"),
            8 =>  println!("Этот код можно отредактировать и запустить!"),
            9 =>  println!("Bạn có thể edit và run code trực tiếp!"),
            10 =>  println!("这段代码是可以编辑并且能够运行的!"),
            _ =>  {},
        }
    }
}

item collections

#![allow(unused)]
fn main() {
impl Summary for Post    

}
#![allow(unused)]
fn main() {
pub fn notify<T: Summary>(item: &T) {
    println!("Breaking news! {}", item.summarize());
}
// is like
pub fn notify(item: &impl Summary) {
    println!("Breaking news! {}", item.summarize());
}

}
#[derive(Debug)]
enum UiObject {
    Button,
    SelectBox,
}

fn main() {
    let objects = [
        UiObject::Button,
        UiObject::SelectBox
    ];

    for o in objects {
        draw(o)
    }
}

fn draw(o: UiObject) {
    println!("{:?}",o);
}

特征对象

pub trait Draw {
    fn draw(&self);
}

pub struct Button {
    pub width: u32,
    pub height: u32,
    pub label: String,
}

impl Draw for Button {
    fn draw(&self) {
        // 绘制按钮的代码
        println!("draw for Button, {}, {}, {}", &self.width, &self.height, &self.label);
    }
}

struct SelectBox {
    width: u32,
    height: u32,
    options: Vec<String>,
}

impl Draw for SelectBox {
    fn draw(&self) {
        // 绘制SelectBox的代码
        println!("draw for Selectbox {}, {}, {:?}", &self.width, &self.height, &self.options);
    }
}


// pub struct Screen {
//     pub components: Vec<Box<dyn Draw>>,
// }
// impl Screen {
//     pub fn run(&self) {
//         for component in self.components.iter() {
//             component.draw();
//         }
//     }
// }

pub struct Screen<T: Draw> {
    pub components: Vec<T>,
}

impl<T> Screen <T>
where T: Draw {
    pub fn run(&self) {
        for component in self.components.iter() {
            component.draw();
        }
    }
}




fn main() {
    let screen = Screen {
        components: vec![
            Box::new(SelectBox {
                width: 75,
                height: 10,
                options: vec![
                    String::from("Yes"),
                    String::from("Maybe"),
                    String::from("No")
                ],
            }),
            Box::new(Button {
                width: 50,
                height: 10,
                label: String::from("OK"),
            }),
        ],
    };

    screen.run();
}

mut

mut example

fnmain() {
    let x :i32 = 48;
    let X :i32 = 480;
    let mut y :&i32        = &x;    // y can be redirected from x to X, but y can not change x
    let      z: &mut &i32 = &mut y  // z can not be redirected, but z can change y
}

different lifetime

fn main() {
    struct MutStr<'a, 'b> {
        s: &'a mut &'b str,
    }

    let mut r: &str = "hello";
    Mutstr{s: &mut r}.s = "world";
    println!("{}", r);
}


title: python

#+STARTUP: overview

Install

prerequirement

sudo apt-get install -y make build-essential libssl-dev zlib1g-dev libbz2-dev \
libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev libncursesw5-dev \
xz-utils tk-dev libffi-dev liblzma-dev python-openssl git

install from source code

go to the offical python3.9 site, down the newest version python package, extract it ./configure make make test sudo make install

create virtualenv

virtualenv

sudo apt install python3-virtualenv virtualenv --python=3.10 venv source venv/bin/activate deactivate

python3-venv

sudo apt install python3-venv python3 -m venv django source venv/bin/activate deactivate

pip

pip freeze > requirement.txt pip install -r requirement.txt

ipython

install ipyton comes error

AttributeError: 'PtkHistoryAdapter' object has no attribute '_loaded'

this is because prompt-toolkit version 2 conflict with ipython, upgrade it with

pip install prompt-toolkit --upgrade

update package

pip list --outdated --format=freeze | grep -v '^\-e' | cut -d = -f 1  | xargs -n1 pip install -U

GPU Driver for linux

install with apt

Am 2022 May 09, monday I install cuda with apt, I don't know if this is ready a offer for all, but I still wirte it down

sudo apt update
sudo apt upgrade
ubuntu-drivers devices
sudo apt install nvidia-driver-510
reboot
watch  -n 0.1 nvidia-smi 

sudo apt install zlib1g nvidia-cuda-toolkit
nvcc -V

pip install virtualenv 
python -m virtualenv dlforcvenv
cd dlforcvenv
source ./bin/activate
pip install torch torchvision torchaudio

pip install notebook
python -m jupyter notebook &
import torch
torch.cuda.is_available(), torch.backends.cudnn.is_available(), torch.cuda.device_count()

install driver 418-server, cuda 10.1, cudnn 7.6.1

1. nouveau to backlist: add following to /etc/modprobe.d/blacklist.conf
   blacklist nouveau
   options nouveau modeset=0

2. sudo update-initramfs -u   

3. sudo apt update
   ubuntu-drivers devices
   sudo apt install nvidia-drivers-418-server
   sudo reboot


   then I will be able to check :   nvidia-smi

4. CUDA
   go to [[https://developer.nvidia.com/cuda-toolkit-archive]]
   select CUDA Toolkit 10.1 update 2 to install
   unmark the Drivers in  CUDA installation

5. emacs ~/.bashrc
   export PATH="/usr/local/cuda-10.1/bin:<span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8889em;vertical-align:-0.1944em;"></span><span class="mord mathnormal" style="margin-right:0.13889em;">P</span><span class="mord mathnormal">A</span><span class="mord mathnormal" style="margin-right:0.13889em;">T</span><span class="mord mathnormal" style="margin-right:0.08125em;">H</span><span class="mord">&quot;</span><span class="mord mathnormal">e</span><span class="mord mathnormal">x</span><span class="mord mathnormal">p</span><span class="mord mathnormal" style="margin-right:0.02778em;">or</span><span class="mord mathnormal">t</span><span class="mord mathnormal">L</span><span class="mord"><span class="mord mathnormal" style="margin-right:0.02778em;">D</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3283em;"><span style="top:-2.55em;margin-left:-0.0278em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight">L</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mord mathnormal" style="margin-right:0.07847em;">I</span><span class="mord mathnormal" style="margin-right:0.00773em;">BR</span><span class="mord mathnormal">A</span><span class="mord mathnormal" style="margin-right:0.00773em;">R</span><span class="mord"><span class="mord mathnormal" style="margin-right:0.22222em;">Y</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3283em;"><span style="top:-2.55em;margin-left:-0.2222em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight" style="margin-right:0.13889em;">P</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mord mathnormal">A</span><span class="mord mathnormal" style="margin-right:0.13889em;">T</span><span class="mord mathnormal" style="margin-right:0.08125em;">H</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">=</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord">&quot;/</span><span class="mord mathnormal">u</span><span class="mord mathnormal" style="margin-right:0.02778em;">sr</span><span class="mord">/</span><span class="mord mathnormal" style="margin-right:0.01968em;">l</span><span class="mord mathnormal">co</span><span class="mord mathnormal">a</span><span class="mord mathnormal" style="margin-right:0.01968em;">l</span><span class="mord">/</span><span class="mord mathnormal">c</span><span class="mord mathnormal">u</span><span class="mord mathnormal">d</span><span class="mord mathnormal">a</span><span class="mspace" style="margin-right:0.2222em;"></span><span class="mbin">−</span><span class="mspace" style="margin-right:0.2222em;"></span></span><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord">10.1/</span><span class="mord mathnormal" style="margin-right:0.01968em;">l</span><span class="mord mathnormal">ib</span><span class="mord">64</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">:</span></span></span></span>LD_LIBRARY_PATH"
   source ~/.bashrc

6. check CUDA
   cd /usr/local/cuda-10.1/samples/1_Utilities/deviceQuery
   sudo make
   ./deviceQuery

   OK if Result = PASS
   or nvcc -V

6. cuDNN
   go to [[https://developer.nvidia.com/rdp/cudnn-download]]
   at least select 7.6.1 for CUDA 10.1
   sudo cp cuda/include/cudnn.h /usr/local/cuda/include/
   sudo cp cuda/lib64/libcudnn* /usr/local/cuda/lib64/
   sudo chmod a+r /usr/local/cuda/include/cudnn.h 

7. sudo apt remove nvidia-*
   reboot

8. download the nvidia driver source file  at
   [[https://www.nvidia.com/Download/index.aspx?lang=en-us]]

9. cd ~/Downloads
   chmod +x ~/Downloads/NVIDIA-Linux-x86_64-450.80.02.run
   sudo ./NVI...

10. sudo apt install python3-pip
    sudo apt install ipython3
    pip3 install pip
    pip3 install tensorflow-gpu
    ipython3
    import tensorflow as tf
    print(tf.test.is_gpu_available())
  1. fixup sometime it can be in the case: the communication with nvidia driver is failed, to fix it, using apt install the driver 418-driver from apt again

  2. check

    import tensorflow as tf
    if (tf.test.is_gpu_available(cuda_only=False, min_cuda_compute_capability=None)==True):
      print("using gpu")
    
import sys
print(sys.version)

Error

'int' object is not callable

trying to assign a variable to the system variable

can't open pip installed package

notebook, or ipython, such package, installed, bu can't open, if the package is in the path, we can start it with python -m package

Python Program collection

useful expression

conditional express

condition = True
x = 1 if condition else 0
print(x)

Large Number Formation


num1 = 100_000_000_000
num2 = 10_000_000
print(f'{num1 + num2 :,}')

open with

with open('pycharm_keybounding.org','r') as f:
    file= f.read()
words = file.split(' ')


enumerate

names = ['one', 'two', 'three', 'four']
for index, name in enumerate(names, start=1):
    print(index,name)

zip

names = ['one', 'two', 'three', 'four']
hero = ['ni', 'wo', 'ta', 'bu']

for name, h in zip(names, hero):
    print(f'{name} is actually {h}')

unpacking tuple

a, b, *_ = (1,2,3, 4,5)
a, b, *f = (1,2,3, 4,5)
c, d, _ = (1,2,3)
print(a)
print(b)

setattr,

getattr

from getpass import getpass
password = getpass('Password:')

python -m model 直接执行model模块

map and for

list1 = [ord(x) for x in 'ABC']
print(list1)

list2 = map(ord, 'ABkkC')
print(list2)

multiply

print('A'*3)
print(['A']*3)
print([['A']]*3)

generator

use yield stead of return

def func (lst):
    lt = []
    for i in lst:
        lt.append( i*i)
    return lt
num = func([ x for x in range(8)])
print(num)
num1 = [ x*x for x in range(8)]
print(num1)


#generator
def funcg (lst):
    for i in lst:
        yield (i*i)

numg = funcg([ x for x in range(8)])
print(numg)
numg1 = ( x*x for x in range(8))
print(numg1)



List

this can not be execute, otherweise it will dead,rekursive of position 0

words = ['big','cat','dog']
for a in words:
    words.insert(0, 'wo')

words = ['big','cat','dog']
for a in words[:]:
    words.insert(0, 'wo')

list creation


# two fast way to create list
a0 = [1]*10
print(a0)
a1 = [1 for x in range(10)]
print(a1)

# every subarray is conneted
ak0 = [[]]*10
print(ak0)
ak0[2].append(3)
print(ak0)

# every subarray is disconneted
ak1 = [[] for x in range(10)]
print(ak1)
ak1[2].append(3)
print(ak1)

Break Points

else sentence after for: after for sentence else can be used

def fun(argument, *argument, **argument)
fun(single_value, tuple, dictionary)

lambda with funtion

def fun(n):
    return lambda x: x+n
print(fun(3)(4))
nonlocal将变量的赋值,且将此值向外层作用域扩展一个范

global 将变量的赋值到程序的全局作用域


_ value: 在交互模式下,上一次打印出来的表达式被赋值给变量 _

import test.py file as a model
import test
so all funtions and parameters can be called as in a test class


python -i test.py 
after execute test.py file, terminal will get into python console, 
and all funtions and parameters can just be called.

Tkinter Vairlaation

buttom

import tkinter as tk

window = tk.Tk()
window.title('my window')
window.geometry('200x200')

var = tk.StringVar()
l = tk.Label(window, bg='yellow', width=20, text='empty')
l.pack()

def print_selection():
    l.config(text='you have selected ' + var.get())

r1 = tk.Radiobutton(window, text='Option A',
                    variable=var, value='A',
                    command=print_selection)
r1.pack()
r2 = tk.Radiobutton(window, text='Option B',
                    variable=var, value='B',
                    command=print_selection)
r2.pack()
r3 = tk.Radiobutton(window, text='Option C',
                    variable=var, value='C',
                    command=print_selection)
r3.pack()


window.mainloop()


checkbutton

import tkinter as tk

window = tk.Tk()
window.title('my window')
window.geometry('200x200')

l = tk.Label(window, bg='yellow', width=20, text='empty')
l.pack()

def print_selection():
    if (var1.get() == 1) & (var2.get() == 0):
        l.config(text='I love only Python ')
    elif (var1.get() == 0) & (var2.get() == 1):
        l.config(text='I love only C++')
    elif (var1.get() == 0) & (var2.get() == 0):
        l.config(text='I do not love either')
    else:
        l.config(text='I love both')

var1 = tk.IntVar()
var2 = tk.IntVar()
c1 = tk.Checkbutton(window, text='Python', variable=var1, onvalue=1, offvalue=0,
                    command=print_selection)
c2 = tk.Checkbutton(window, text='C++', variable=var2, onvalue=1, offvalue=0,
                    command=print_selection)
c1.pack()
c2.pack()


window.mainloop()


import tkinter as tk

window = tk.Tk()
window.title('my window')
window.geometry('200x200')

l = tk.Label(window, text='', bg='yellow')
l.pack()
counter = 0
def do_job():
    global counter
    l.config(text='do '+ str(counter))
    counter+=1

menubar = tk.Menu(window)
filemenu = tk.Menu(menubar, tearoff=0)
menubar.add_cascade(label='File', menu=filemenu)
filemenu.add_command(label='New', command=do_job)
filemenu.add_command(label='Open', command=do_job)
filemenu.add_command(label='Save', command=do_job)
filemenu.add_separator()
filemenu.add_command(label='Exit', command=window.quit)

editmenu = tk.Menu(menubar, tearoff=0)
menubar.add_cascade(label='Edit', menu=editmenu)
editmenu.add_command(label='Cut', command=do_job)
editmenu.add_command(label='Copy', command=do_job)
editmenu.add_command(label='Paste', command=do_job)

submenu = tk.Menu(filemenu)
filemenu.add_cascade(label='Import', menu=submenu, underline=0)
submenu.add_command(label="Submenu1", command=do_job)

window.config(menu=menubar)

window.mainloop()


canvas (cannt load img)

import tkinter as tk

window = tk.Tk()
window.title('my window')
window.geometry('200x200')

canvas = tk.Canvas(window, bg='blue', height=100, width=200)
image_file = tk.PhotoImage(file='ins.gif')
image = canvas.create_image(10, 10, anchor='nw', image=image_file)
x0, y0, x1, y1= 50, 50, 80, 80
line = canvas.create_line(x0, y0, x1, y1)
oval = canvas.create_oval(x0, y0, x1, y1, fill='red')
arc = canvas.create_arc(x0+30, y0+30, x1+30, y1+30, start=0, extent=180)
rect = canvas.create_rectangle(100, 30, 100+20, 30+20)
canvas.pack()

def moveit():
    canvas.move(rect, 0, 2)

b = tk.Button(window, text='move', command=moveit).pack()


window.mainloop()

frame


import tkinter as tk

window = tk.Tk()
window.title('my window')
window.geometry('200x200')
tk.Label(window, text='on the window').pack()

frm = tk.Frame(window)
frm.pack()
frm_l = tk.Frame(frm, )
frm_r = tk.Frame(frm)
frm_l.pack(side='left')
frm_r.pack(side='right')

tk.Label(frm_l, text='on the frm_l1').pack()
tk.Label(frm_l, text='on the frm_l2').pack()
tk.Label(frm_r, text='on the frm_r1').pack()
window.mainloop()

list



import tkinter as tk

window = tk.Tk()
window.title('my window')
window.geometry('200x200')

var1 = tk.StringVar()
l = tk.Label(window, bg='yellow', width=4, textvariable=var1)
l.pack()

def print_selection():
    value = lb.get(lb.curselection())
    var1.set(value)

b1 = tk.Button(window, text='print selection', width=15,
              height=2, command=print_selection)
b1.pack()

var2 = tk.StringVar()
var2.set((11,22,33,44))
lb = tk.Listbox(window, listvariable=var2)
list_items = [1,2,3,4]
for item in list_items:
    lb.insert('end', item)
lb.insert(1, 'first')
lb.insert(2, 'second')
lb.delete(2)
lb.pack()

window.mainloop()


scale


import tkinter as tk

window = tk.Tk()
window.title('my window')
window.geometry('200x200')

l = tk.Label(window, bg='yellow', width=20, text='empty')
l.pack()

def print_selection(v):
    l.config(text='you have selected ' + v)

s = tk.Scale(window, label='try me', from_=5, to=11, orient=tk.HORIZONTAL,
             length=200, showvalue=0, tickinterval=2, resolution=0.01, command=print_selection)
s.pack()

window.mainloop()


decorator

1, @后没有参数,则被修饰函数名被传到修饰函数作参数 2, @后有参数,在该参数被传到修饰函数作参数,而被修饰函数可在其定义内被接收

def log(func):
    def wrapper(*args, **kw):
        print('call function %s():' % func.__name__)
        return func(*args, **kw)
    return wrapper

def loog(text):
    def decorator(fun):
        def wrapper(*args, **kw):
            print('kkcall function %s with %s():' % (fun.__name__, text))
            return fun(*args, **kw)
        return wrapper
    return decorator



@loog('exit')
def now():
    print("now to start")

now()

functools

import functools
int2 = functools.partial(int, base=3)
print(int2('1211'))

Polymorphism

class Animal(object):
    def __init__(self):
        self.name ='Animal name'

    def run(self):
        print('Animal is running')

class Dog(Animal):
    def __init__(self):
        self.name ='Dog name'
    def run(self):
        print('Dog is running')

class Cat(Animal):
    def __init__(self):
        self.name ='Cat name'
    def run(self):
        print('Cat is running')

class Tortoise(Animal):
    def __init__(self):
        self.name ='Tortoise name'
    def run(self):
        print('Tortoise is running slowly')

# Polymorphism, all Class or instance will be checked the best passing
# mothode or character
def run_twice(a):
    a.run()

def name(b):
    print(b.name)

dog = Dog()
cat = Cat()


run_twice(Animal())
run_twice(Dog())
run_twice(Cat())
run_twice(dog)

name(Animal())
name(Dog())
name(dog)

generator

def something():
    result = []
    for _ in range(10):
        result.append(2)
    return result
print(something())


def iter_some():
    x = 0
    for _ in range(10):
        yield x
        x += 1
a = iter_some()
print(next(a))
print(next(a))
print(next(a))


def fib ():
    a = b = 1
    yield a
    yield b
    while True:
        a, b = b, a+b
        yield b


for var in fib():
    if var > 100:
        break
    print(var)



pdb

  1. python -m pdb test.py

step by step with n,

  1. import pdb

pdb.set~trace~() 设置断点

Copy

copying fundmental vaiable will creat a new id for assigned varible, copy = [:] for object will create also a new id for new object, but not for nested object deepcopy will also creat id for nested object in copyed object

Decorator

decorator just rewrite the function, using call function as argument

def decorator_function(original_function):
    def wrapper_function(*arg, **kwargs):
        print("using wrapper, and  the name is {}, and the age".format(original_function.__name__))
        return original_function(*arg, **kwargs)
    return wrapper_function

class decorator_class(object):
    def __init__(self, original_function):
        self.original_function = original_function
    def __call__(self, *arg, **kwargs):
        print("using the decorator class")
        return self.original_function(*arg, **kwargs)

print("////////function decor without augurment//////////////////////")
def display():
    print("display this")
display = decorator_function(display)
display()
print("////////decorator decor without augurment//////////////////////")
@decorator_function
def display1():
    print("display1 this")
display1()
print("////////function decor with augurment//////////////////////")
def display_info(name, age):
    print("display the name is {}, and the age is {}".format(name, age))
display_info = decorator_function(display_info)
display_info("Xiang", 21)
print("////////decorator decor with augurment//////////////////////")
@decorator_function
def display_info1(name, age):
    print("display the name is {}, and the age is {}".format(name, age))
display_info1("Xiang", 21)
print("/////////class decorator decor/////////////////////")
@decorator_class
def display_info_class(name, age):
    print("display the name is {}, and the age is {}".format(name, age))
display_info_class("Xiang", 21)
print("////////class function decor//////////////////////")
def display_info_class(name, age):
    print("display the name is {}, and the age is {}".format(name, age))
display_info_class1 = decorator_class(display_info_class)
display_info_class1("Xiang", 21)



with * **

def function_with_one_star(*d):
    print(d)

def function_with_two_stars(**d):
    print(d)

function_with_one_star(1,2,3)

function_with_two_stars(a=1, b=2, c=3)


(1, 2, 3)
{'a': 1, 'b': 2, 'c': 3}

Python Numpy with ~

Wenn we want to filter the we wanted from a np.array, we can define the filter with boolen in a np.array,

import numpy as np
x = np.arange(25).reshape(5,5)
print(x)

[[ 0  1  2  3  4]
 [ 5  6  7  8  9]
 [10 11 12 13 14]
 [15 16 17 18 19]
 [20 21 22 23 24]]

Or

import numpy as np
xx = np.linspace(0, 24, 25).reshape(5,5)
print(xx)

[[ 0.  1.  2.  3.  4.]
 [ 5.  6.  7.  8.  9.]
 [10. 11. 12. 13. 14.]
 [15. 16. 17. 18. 19.]
 [20. 21. 22. 23. 24.]]

With np.linspace is float number, but arange is int number

import numpy as np
x = np.arange(25).reshape(5,5)
y = np.array([False, False, True, True, False])
print(x[y,2])

[12 17]

according to y = np.array([False, False, True, True, False]) to filter the true position in the third column.

if we want the false position in the third column, with ~ on the filter array

import numpy as np
x = np.arange(25).reshape(5,5)
y = np.array([False, False, True, True, False])
print(x[~y,2])

[ 2  7 22]

turtle movement


import turtle
turtle.setup(650, 350, 200, 200)
turtle.penup()
turtle.fd(-250)
turtle.pendown()
turtle.pensize(25)
turtle.pencolor("purple")
turtle.seth(-40)
for i in range(4):
    turtle.circle(40, 80)
    turtle.circle(-40, 80)
turtle.circle(40, 80/2)
turtle.fd(40)
turtle.circle(16, 180)
turtle.fd(40*2/3)
turtle.done()


tempertur converse

#TempConver.py
TempStr = input('请输入带有符号的温度值:')
if TempStr[-1] in ['F', 'f']:
    C = (eval(TempStr[0:-1]) - 32)/1.8
    print('转换后的温度值为{:.2f}C'.format(C))
elif TempStr[-1] in ['C', 'c']:
    F = 1.8*eval(TempStr[0:-1]) + 32
    print('转换后的温度值为{:.2f}F'.format(F))
else:
    print('输入有误')


import turtle, time
def drawGap():
    turtle.penup()
    turtle.fd(5)
def drawLine(draw):
    drawGap()
    turtle.pendown() if draw else turtle.penup()
    turtle.fd(40)
    drawGap()
    turtle.right(90)
def drawDigit(digit):
    drawLine(True) if digit in [2,3,4,5,6,8,9] else drawLine(False)
    drawLine(True) if digit in [0,1,3,4,5,6,7,8,9] else drawLine(False)
    drawLine(True) if digit in [0,2,3,5,6,8,9] else drawLine(False)
    drawLine(True) if digit in [0,2,6,8] else drawLine(False)
    turtle.left(90)
    drawLine(True) if digit in [0,4,5,6,8,9] else drawLine(False)
    drawLine(True) if digit in [0,2,3,5,6,7,8,9] else drawLine(False)
    drawLine(True) if digit in [0,1,2,3,4,7,8,9] else drawLine(False)
    turtle.left(180)
    turtle.penup()
    turtle.fd(20)
# def drawDate(date):
#     for i in date:
#         drawDigit(eval(i))
# def main():
def drawDate(date):
    turtle.pencolor("red")
    for i in date:
        if i == '-':
            turtle.write('年', font=("Arial", 18, "normal"))
            turtle.pencolor("green")
            turtle.fd(40)
        elif i == '=':
            turtle.write('月', font=("Arial", 18, "normal"))
            turtle.pencolor("blue")
            turtle.fd(40)
        elif i == '+':
            turtle.write('日', font=("Arial", 18, "normal"))
        else:
            drawDigit(eval(i))
def main():
    turtle.setup(800,350,200,200)
    turtle.penup()
    turtle.fd(-300)
    turtle.pensize(5)
    # drawDate('20181010')
    drawDate(time.strftime("%Y-%m=%d+",time.gmtime()))
    turtle.hideturtle()
    turtle.done()
main()

pandas DataFrame merge

merge in pandas DataFrame is very similar like join in SQL.

DataFrame.merge(right,
                how='inner', 
                on=None,
                left_on=None,
                right_on=None, 
                left_index=False,
                right_index=False, 
                sort=False,
                suffixes=('_x', '_y'),
                copy=True,
                indicator=False, 
                validate=None)[source]

how = 'inner', 'outer', 'left', 'right' default is 'inner' inner: interaction set output: union set left : all left right : all right

if right~on~, left~on~, and on is not given, the merge is on the index(row). we use the frist column from left and right dataframe to merge, just like the example. left: 'one' has 0, 1 right: 'one' has 1, 2, 3 the interaction set is only 1 all columns will be just added together

import pandas as pd
dd = {'one':[0, 1 ], 'two':[0, 0], 'three':[1, 1]}
a = pd.DataFrame(data= dd)
b = pd.DataFrame({'zero':[0,0,0], 'one':[1,2,3 ], 'two':[0,0,0 ]})
print(a)
print(b)
print(a.merge(b))
   one  two  three
0    0    0      1
1    1    0      1
   zero  one  two
0     0    1    0
1     0    2    0
2     0    3    0
   one  two  three  zero
0    1    0      1     0

the can also be merge on columns, for each compare elemenet in column with out repeated key

dd = {'one':[0, 1 ], 'two':[0, 0], 'three':[1, 1]}
a = pd.DataFrame(data= dd)
b = pd.DataFrame({'zero':[0,0,0], 'one':[1,2,3 ], 'two':[0,0,0 ]})
print(a)
print(b)
print(a.merge(b, on='one', how='inner'))

   one  two  three
0    0    0      1
1    1    0      1
   zero  one  two
0     0    1    0
1     0    2    0
2     0    3    0
   one  two_x  three  zero  two_y
0    1      0      1     0      0

if with repeated key, the number will be multipy by its occurrence,

dd = {'one':[0, 1 ], 'two':[0, 0], 'three':[1, 1]}
a = pd.DataFrame(data= dd)
b = pd.DataFrame({'zero':[0,0,0], 'one':[1,2,3 ], 'two':[0,0,0 ]})
print(a)
print(b)
print(a.merge(b, on='two', how='inner'))
   one  two  three
0    0    0      1
1    1    0      1
   zero  one  two
0     0    1    0
1     0    2    0
2     0    3    0
   one_x  two  three  zero  one_y
0      0    0      1     0      1
1      0    0      1     0      2
2      0    0      1     0      3
3      1    0      1     0      1
4      1    0      1     0      2
5      1    0      1     0      3

filp

see numpy document numpy.flip

import numpy as np
A = np.array([[1,2,3], [4,5,6], [7,8,9]])
print(A)
print(A[::-1])
print(np.all(A[::-1] == np.flip(A, 0)))


[[1 2 3]
 [4 5 6]
 [7 8 9]]
[[7 8 9]
 [4 5 6]
 [1 2 3]]
True
from pprint import pprint
import inspect
import time
pprint(inspect.getmembers(time))

@property

@property: Declares the method as a property.
@<property-name>.setter: Specifies the setter method for a property that sets the value to a property.
@<property-name>.deleter: Specifies the delete method as a property that deletes a property.  

python automotion

system manipulation

os.getcwd()

import os
print(os.getcwd())
/home/silin/Dropbox/LiteraturPrograme/content

os.chdir()

# import os
# os.chdir("../../Schreibtisch")
# print(os.getcwd())

os.listdir()

print(os.listdir())
[]

PyTorch

Basic

cpu with cuda.gpu


import torch
import time
print(torch.__version__)
print(torch.cuda.is_available)

a = torch.randn(10000, 1000)
b = torch.randn(1000, 2000)

t0 = time.time()
c = torch.matmul(a, b)
t1 = time.time()
print(a.device, t1-t0, c.norm(2))

device = torch.device('cuda')
a = a.to(device)
b = b.to(device)

t0 = time.time()
c = torch.matmul(a, b)
t2 = time.time()
print(a.device, t2-t0, c.norm(2))


t0 = time.time()
c = torch.matmul(a, b)
t2 = time.time()
print(a.device, t2-t0, c.norm(2))

auto Derivative

import torch
from torch import autograd

x = torch.tensor(1.)
a = torch.tensor(1. , requires_grad=True)
b = torch.tensor(2. , requires_grad=True)
c = torch.tensor(3. , requires_grad=True)

y = a**2*x + b*x + c

print('before:', a.grad, b.grad, c.grad)
grad = autograd.grad(y, [a,b,c])
print('after:', grad[0], grad[1], grad[2])

small example

import torch

x = torch.ones(2,2,requires_grad=True)
y = x +2
z = y*y*3
out = z.mean()
out.backward()
print(x.grad)

\begin{equation}
x = 
  \left(
  \begin{array}{cc}
          1  & 1  \\
          1  & 1 \\
  \end{array}
  \right)
\end{equation}
\begin{equation}
y =    2 + x =
  \left(
  \begin{array}{cc}
          3  & 3  \\
          3  & 3 \\
  \end{array}
  \right)
\end{equation}
\begin{equation}
z =   3*y*y =
  \left(
  \begin{array}{cc}
          27  & 27  \\
          27  & 27 \\
  \end{array}
  \right)
\end{equation}

x.grad is to say :

Function

x = x.new~ones~(4,3)

Iterator DataLoader

here, THE i is the number of iterations, each iteration has 20 iter

import torch
import numpy as np

i = np.array([a for a in range(100)])
i = torch.from_numpy(i)

test = torch.utils.data.DataLoader(i, batch_size=20,shuffle=False)
testiter = iter(test)

for k, data in enumerate(testiter):
    print(k)


torch.max

the return is a namedtuple dim = 0, 1, maximum of rows or columns

import torch
i = torch.randn(3,4)
print(torch.max(i, 0))
print(torch.max(i, 1))

exsample 3 ploy

import torch
import math


class Polynomial3(torch.nn.Module):
    def __init__(self):
        """
        In the constructor we instantiate four parameters and assign them as
        member parameters.
        """
        super().__init__()
        self.a = torch.nn.Parameter(torch.randn(()))
        self.b = torch.nn.Parameter(torch.randn(()))
        self.c = torch.nn.Parameter(torch.randn(()))
        self.d = torch.nn.Parameter(torch.randn(()))

    def forward(self, x):
        """
        In the forward function we accept a Tensor of input data and we must return
        a Tensor of output data. We can use Modules defined in the constructor as
        well as arbitrary operators on Tensors.
        """
        return self.a + self.b * x + self.c * x ** 2 + self.d * x ** 3

    def string(self):
        """
        Just like any class in Python, you can also define custom method on PyTorch modules
        """
        return f'y = {self.a.item()} + {self.b.item()} x + {self.c.item()} x^2 + {self.d.item()} x^3'


# Create Tensors to hold input and outputs.
x = torch.linspace(-math.pi, math.pi, 2000)
y = torch.sin(x)

# Construct our model by instantiating the class defined above
model = Polynomial3()

# Construct our loss function and an Optimizer. The call to model.parameters()
# in the SGD constructor will contain the learnable parameters of the nn.Linear
# module which is members of the model.
criterion = torch.nn.MSELoss(reduction='sum')
optimizer = torch.optim.SGD(model.parameters(), lr=1e-6)
for t in range(2000):
    # Forward pass: Compute predicted y by passing x to the model
    y_pred = model(x)

    # Compute and print loss
    loss = criterion(y_pred, y)
    if t % 100 == 99:
        print(t, loss.item())

    # Zero gradients, perform a backward pass, and update the weights.
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()

print(f'Result: {model.string()}')


packages

matplotlib.plot

two linear plot

import numpy as np
import random
from matplotlib import pyplot as plt

a = np.array([ x for x in range(10)])
b = np.array([[random.randint(0,10) for x in range(10)],[random.randint(0,10) for x in range(10)]])
plt.plot(a,b.T)
plt.show()


simplest linear plot

import matplotlib.pyplot as plt
plt.plot([1,2,3,4])
plt.ylabel('some numbers')
plt.show()


simplest point plot

import matplotlib.pyplot as plt
plt.plot([1,2,3,4], [1,4,9,16], 'ro')
plt.axis([0, 6, 0, 20])
plt.show()


simplest function plot

import numpy as np
import matplotlib.pyplot as plt

# evenly sampled time at 200ms intervals
t = np.arange(0., 5., 0.2)

# red dashes, blue squares and green triangles
plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')
plt.show()


simplest subplot

import numpy as np
import matplotlib.pyplot as plt

def f(t):
    return np.exp(-t) * np.cos(2*np.pi*t)

t1 = np.arange(0.0, 5.0, 0.1)
t2 = np.arange(0.0, 5.0, 0.02)

plt.figure(1)
plt.subplot(211)
plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k')

plt.subplot(212)
plt.plot(t2, np.cos(2*np.pi*t2), 'r--')
plt.show()


histogram plot with cusomised legend

import numpy as np
import matplotlib.pyplot as plt

# Fixing random state for reproducibility
np.random.seed(19680801)

mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)

# the histogram of the data
n, bins, patches = plt.hist(x, 50, normed=1, facecolor='g', alpha=0.75)


plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title('Histogram of IQ')
plt.text(60, .025, r'$\mu=100,\ \sigma=15$')
plt.axis([40, 160, 0, 0.03])
plt.grid(True)
plt.show()


histogram plot

import numpy as np
import matplotlib.pyplot as plt

# Fixing random state for reproducibility
np.random.seed(19680801)

mu, sigma = 100, 15
x = mu + sigma * np.random.randn(100000)

# the histogram of the data
n, bins, patches = plt.hist(x, 50, facecolor='g')

plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title('Histogram of IQ')
#plt.text(60, .025, r'$\mu=100,\ \sigma=15$')
#plt.axis([40, 160, 0, 0.03])
#plt.grid(True)
plt.show()



histogram y axis with log index


import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import NullFormatter  # useful for `logit` scale

# Fixing random state for reproducibility
np.random.seed(19680801)

# make up some data in the interval ]0, 1[
y = np.random.normal(loc=0.5, scale=0.4, size=1000)
y = y[(y > 0) & (y < 1)]
y.sort()
x = np.arange(len(y))

# plot with various axes scales
plt.figure(1)

# linear
plt.subplot(221)
plt.plot(x, y)
plt.yscale('linear')
plt.title('linear')
plt.grid(True)


# log
plt.subplot(222)
plt.plot(x, y)
plt.yscale('log')
plt.title('log')
plt.grid(True)


# symmetric log
plt.subplot(223)
plt.plot(x, y - y.mean())
plt.yscale('symlog', linthreshy=0.01)
plt.title('symlog')
plt.grid(True)

# logit
plt.subplot(224)
plt.plot(x, y)
plt.yscale('logit')
plt.title('logit')
plt.grid(True)
# Format the minor tick labels of the y-axis into empty strings with
# `NullFormatter`, to avoid cumbering the axis with too many labels.
plt.gca().yaxis.set_minor_formatter(NullFormatter())
# Adjust the subplot layout, because the logit one may take more space
# than usual, due to y-tick labels like "1 - 10^{-3}"
plt.subplots_adjust(top=0.92, bottom=0.08, left=0.10, right=0.95, hspace=0.25, wspace=0.35)

plt.show()


a example of mean standrad deviation plotting

import matplotlib.pyplot as plt;
import numpy as np
import scipy.stats
import scipy as sp
from scipy import integrate
from scipy.optimize import curve_fit

data = np.genfromtxt('Highz_SN_data.txt');

redshift = np.array([data[:,2]])
mu = np.array([data[:,3]])
velocity = np.array([data[:,4]])
redshift_mean = np.mean(redshift)
mu_mean = np.mean(mu)
velocity_mean = np.mean(velocity)
redshift_std = np.std(redshift)
mu_std = np.std(mu)
velocity_std = np.std(velocity)
para = ["redshift", "mu", "velocity"]
x_pos = np.arange(len(para))
ctes = [redshift_mean, mu_mean, velocity_mean]
error = [redshift_std, mu_std, velocity_std]


fig, ax = plt.subplots()
ax.bar(x_pos, ctes, yerr=error, align='center', alpha=0.5, ecolor='black', capsize=10)
ax.set_ylabel('Coefficient of Thermal Expansion ($\degree C^{-1}$)')
ax.set_xticks(x_pos)
ax.set_xticklabels(para)
ax.set_title('Coefficent of Thermal Expansion (CTE) of Three Metals')
ax.yaxis.grid(True)

# Save the figure and show
plt.tight_layout()
plt.savefig('bar_plot_with_error_bars.png')
plt.show()

pandas

plot.scatter()

import pandas as pd
import numpy as np
a = pd.DataFrame(np.random.rand(3,2))
print(a)
a.plot.scatter(x=0, y = 1)


Tensorflow 1

Constand additional und multiply

addition

import tensorflow as tf
a = tf.constant([1.0, 2.0])
b = tf.constant([3.0, 4.0])

a_m = tf.constant([[1.0, 2.0]])
b_m = tf.constant([[3.0], [4.0]])

result_add = a + b
result_multpl = tf.matmul(a_m, b_m)

with tf.Session() as sess:
    print (sess.run(result_add))
    print (sess.run(result_multpl))

print (result_add)
print (result_multpl)

mpppultiply


import tensorflow as tf
#创建常量
m1= tf.constant([[3,3]])
m2=tf.constant([[1],[2]])
#相乘
product = tf.matmul(m1,m2)
print(product)

#定义一个会话,启动默认图
sess = tf.Session()
#调用sess,执行乘法运算
result = sess.run(product)
print(result)
#不要忘了关闭sess
sess.close()

with tf.Session() as sess:
    result = sess.run(product)
    print(result)
#使用with不需要专门关闭sess


Variable

the first using of variable & subtract add

  import tensorflow as tf
  x = tf.Variable([1,2])
  a = tf.constant([3,3])
  sub = tf.subtract(x,a)
  add = tf.add(x,sub)
# 对于变量,要初始化init
  init = tf.global_variables_initializer()
  with tf.Session() as sess:
      sess.run(init)
      print(sess.run(sub))
      print(sess.run(add))


assign a value for variable and update & assign

#..................................变量计算
#变量可以被起名,初始化为0
import tensorflow as tf
state = tf.Variable(0, name = 'counter')
new_value = tf.add(state,1)
#赋值功能assign
update = tf.assign(state,new_value)
init = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init)
    print(state)
    for _ in range(5):
        sess.run(update)
        print(sess.run(state))
        print(sess.run(update))


fetch and Feed &placeholder

import tensorflow as tf
# Fetch 在一个会话里执行多个op
input1 = tf.constant(3.0)
input2 = tf.constant(2.0)
input3 = tf.constant(5.0)

add = tf.add(input2,input3)
mul = tf.multiply(input1,add)

with tf.Session() as sess:
    result = sess.run([add,mul])  #有[]
    print(result)

#------------------Feed
#创建占位符
input4= tf.placeholder(tf.float32)
input5 = tf.placeholder(tf.float32)
output = tf.multiply(input4, input5)
with tf.Session() as sess:
    print(sess.run(output,feed_dict = {input4:[7.0],input5:[2.0]}))  #随后赋值是用字典的方式进行的feed_dict = {input4:[7.0],input5:[2.0]}, 数字还加了方括号.


Tuning

change learing rate

#coding:utf-8

import tensorflow as tf
LEARING_RATE_BASE = 0.1
LEARING_RATE_DECAY = 0.99
LEARING_RATE_STEP= 1

global_step = tf.Variable(0,trainable = False)
learning_rate = tf.train.exponential_decay(LEARING_RATE_BASE, global_step,
LEARING_RATE_STEP, LEARING_RATE_DECAY, staircase = True)

w = tf.Variable(tf.constant(5, dtype = tf.float32))
loss = tf.square(w+1)

train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss,global_step = global_step)

with tf.Session() as sess:
    init_op = tf.global_variables_initializer()
    sess.run(init_op)
    for i in range(40):
        sess.run(train_step)
        learnin_rate_val = sess.run(learning_rate)
        global_step_val = sess.run(global_step)
        w_val = sess.run(w)
        loss_val = sess.run(loss)
        print(" After {} steps: global_step is {}, w is {}, learnin_rate is {}, loss is {}"
.format(i, global_step_val, w_val, learnin_rate_val, loss_val))


learing rate for loss

import tensorflow as tf
w = tf.Variable(tf.constant(5,dtype=tf.float32))
loss = tf.square(w+1)
train_step = tf.train.GradientDescentOptimizer(0.2).minimize(loss)

with tf.Session() as sess:
    init_op=tf.global_variables_initializer()
    sess.run(init_op)
    for i in range(50):
        sess.run(train_step)
        w_var = sess.run(w)
        loss_val = sess.run(loss)
        print("After {} steps: w is {}, loss is {}".format(i,w_var,loss_val))
        #print("After %s steps: w is %f, loss is %f." %(i,w_var, loss_val))


train examples

the first train case

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
#生成随机数据
x_date = np.random.rand(100)
y_date = x_date*0.4 + 2

#构造线性模型
b = tf.Variable(0.)
k = tf.Variable(0.)
y = k*x_date + b

#构造二次代价函数
loss = tf.reduce_mean(tf.square(y_date-y))
#定义梯度下降的优化器
optimizer = tf.train.GradientDescentOptimizer(0.2)
#定义一个最小化代价函数
train = optimizer.minimize(loss)
init = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init)
    for steps in range(201):
        sess.run(train)
        if steps%20 == 0:
            print(steps, sess.run([k,b]))
    prediction_value = sess.run(y)
    plt.figure()
    plt.scatter(x_date, y_date)
    plt.plot(x_date,prediction_value,'r-',lw=5)
    plt.show()



non linear regression case

#----------------------------非线性回归
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

#构造数据
x_date = np.linspace (-0.5,0.5,100)[:,np.newaxis] #np.newaxis 功能同None,将行变列
noise = np.random.normal(0,0.02,x_date.shape)
y_date = np.square(x_date)+noise

x = tf.placeholder(tf.float32,[None,1])
y = tf.placeholder(tf.float32,[None,1])

#构建神经网络
Weight_L1 = tf.Variable(tf.random_normal([1,10]))
Biase_L1 = tf.Variable(tf.zeros([1,10]))
Wx_plus_b_L1 = tf.matmul(x,Weight_L1)+Biase_L1
L1 = tf.nn.tanh(Wx_plus_b_L1)

#定义输出层
Weight_L2 = tf.Variable(tf.random_normal([10,1]))
Biase_L2 = tf.Variable(tf.zeros([1,1]))
Wx_plus_b_L2 = tf.matmul(L1,Weight_L2)+ Biase_L2
prediction = tf.nn.tanh(Wx_plus_b_L2)

#二次代价函数
loss = tf.reduce_mean(tf.square(y-prediction))
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    for _ in range(2000):
        sess.run(train_step,feed_dict={x:x_date,y:y_date})

    #训练好后,用来做预测
    prediction_value = sess.run(prediction,feed_dict={x:x_date})
    plt.figure()
    plt.scatter(x_date, y_date)
    plt.plot(x_date,prediction_value,'r-',lw=5)
    plt.show()


the first train with data for accuary

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
#载入数据集
mnist= input_data.read_data_sets('MNIST_data', one_hot = True)

#设定每个批次的大小
batch_size = 100
#计算总共的批次
n_batch = mnist.train.num_examples // batch_size

#参数统计
def variable_summries(var):
    with tf.name_scope('summaries'):
        mean = tf.reduce_mean(var)
        tf.summary.scalar('mean',mean)
        with tf.name_scope('stddev'):
            stddev = tf.sqrt(tf.reduce_mean(tf.square(var-mean)))
        tf.summary.scalar('stddev',stddev)
        tf.summary.scalar('max',tf.reduce_max(var))
        tf.summary.scalar('min',tf.reduce_min(var))
        tf.summary.histogram('histogram',var)

#命名空间
with tf.name_scope('input'):
    x = tf.placeholder(tf.float32,[None,784])
    y = tf.placeholder(tf.float32,[None,10])

with tf.name_scope('layers'):
    with tf.name_scope('wight'):
        W = tf.Variable(tf.truncated_normal([784,10]))
        variable_summries(W)
    with tf.name_scope('biases'):
        B = tf.Variable(tf.zeros([10])+0.1)
        variable_summries(B)
    with tf.name_scope('wx_plus_b'):
        wx_plus_b=tf.matmul(x,W)+B
    with tf.name_scope('softmax'):    
        prediction = tf.nn.tanh(wx_plus_b)

#定义二次代价函数
#loss = tf.reduce_mean(tf.square(y-prediction))
#重新定义对数(交叉熵)
with tf.name_scope('loss'):
    loss =tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=prediction))
    tf.summary.scalar('loss',loss)
#使用梯度下降法

with tf.name_scope('train'):
    train_step = tf.train.GradientDescentOptimizer(0.2).minimize(loss)
#    train_step = tf.train.AdamOptimizer(0.05).minimize(loss)
#初始化
init = tf.global_variables_initializer()

#测试准确率
with tf.name_scope('accuracy'):
    with tf.name_scope('correct_prediction'):
        correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(prediction,1))
    with tf.name_scope('accuracy'):
        accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
        tf.summary.scalar('accuracy',accuracy)

#合并summary
merged = tf.summary.merge_all()
        #训练开始
with tf.Session() as sess:
    writer = tf.summary.FileWriter('pics/',sess.graph)
    sess.run(init)
    for epoch in range(51):
        for batch in range(n_batch):
            batch_xs, batch_ys = mnist.train.next_batch(batch_size)
            summary,_ = sess.run([merged,train_step], feed_dict={x:batch_xs, y:batch_ys})
#            writer.add_summary(summary,batch)
        writer.add_summary(summary,epoch)
        acc = sess.run(accuracy,feed_dict={x:mnist.test.images, y:mnist.test.labels})
        print("准确率为: 在"+str(epoch)+"回,"+str(acc))



a simple CNN case

import tensorflow as tf
import numpy as np
BATCH_SIZE = 8
seed = 23455

rng = np.random.RandomState(seed)
X = rng.rand(32, 2)
Y = [[int(X0+X1 < 1)] for (X0, X1) in X]
# print ("X is :", X)
# print ("Y is :", Y)

x = tf.placeholder(tf.float32, shape = (None, 2))
y_ = tf.placeholder(tf.float32, shape = (None, 1))

w1 = tf.Variable(tf.random_normal([2,3], stddev=1, seed=1))
w = tf.Variable(tf.random_normal([3,3], stddev=1, seed=1))
w2 = tf.Variable(tf.random_normal([3,1], stddev=1, seed=1))

a = tf.matmul(x,w1)
b = tf.matmul(a,w)
y = tf.matmul(b,w2)

loss = tf.reduce_mean(tf.square(y-y_))
train_step = tf.train.GradientDescentOptimizer(0.001).minimize(loss)

with tf.Session() as sess:
    init_op = tf.global_variables_initializer()
    sess.run(init_op)
    print("w1 is :", sess.run(w1))
    print("w is :", sess.run(w))
    print("w2 is :", sess.run(w2))

    steps= 30000
    for i in range(steps):
        start = (i*BATCH_SIZE) % 32
        end = start + BATCH_SIZE
        sess.run(train_step, feed_dict={x:X[start:end], y_:Y[start:end]})
        if i % 5000 == 0:
            total_loss = sess.run(loss, feed_dict={x:X, y_:Y})
            print("After %d training steps, loss on all data is %g" %(i,total_loss))
    print("\n")
    print("w1 is :", sess.run(w1))
    print("w is :", sess.run(w))
    print("w2 is :", sess.run(w2))

CNN train

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

mnist=input_data.read_data_sets("MNIST_data",one_hot = True)

batch_size = 100
n_batch = mnist.train.num_examples // batch_size

#初始化权值
def weight_variable(shape):
    return tf.Variable(tf.truncated_normal(shape,stddev =0.01))

#初始化偏置
def bias_variable(shape):
    return tf.Variable(tf.constant(0.1,shape= shape))

#定义卷积层
def conv2d(x,W):
    return tf.nn.conv2d(x,W,strides=[1,1,1,1],padding="SAME") 

#池化层定义
def max_pool_2x2(x):
    return tf.nn.max_pool(x,ksize =[1,2,2,1],strides=[1,2,2,1], padding = "SAME")

x = tf.placeholder(tf.float32,[None, 784])
y = tf.placeholder(tf.float32,[None,10])

x_image = tf.reshape(x,[-1,28,28,1])

#初始化第一个卷积层的权值和偏置,输入其要求的形状
W_convl = weight_variable([5,5,1,32]) #5x5的采样窗口大小,1通道对黑白,3通道对彩色
b_convl = bias_variable([32])

#现在卷积
h_conv1 = tf.nn.relu(conv2d(x_image,W_convl) +b_convl)
#现在池化
h_pool1 = max_pool_2x2(h_conv1) 


W_convl2 = weight_variable([5,5,32,64]) #5x5的采样窗口大小,1通道对黑白,3通道对彩色
b_convl2 = bias_variable([64])

#现在卷积
h_conv2 = tf.nn.relu(conv2d(h_pool1 ,W_convl2) +b_convl2)
#现在池化
h_pool2 = max_pool_2x2(h_conv2)

#池化后将结果扁平化处理,以便输入网络
h_pool2_flat = tf.reshape(h_pool2, [-1,7*7*64])

#建立第一个神经网络的全连接层,初始化其权重和偏置
W_fcl = weight_variable([7*7*64, 100])
b_fcl = bias_variable([100])

#第一层的计算
h_fcl = tf.nn.relu(tf.matmul(h_pool2_flat, W_fcl) + b_fcl)

#dropout
keep_prob = tf.placeholder(tf.float32)
h_fcl_drop = tf.nn.dropout(h_fcl, keep_prob)

#建立第二个神经层
W_fc2 = weight_variable([100,10])
b_fc2 = bias_variable([10])
prediction = tf.nn.softmax(tf.matmul(h_fcl_drop, W_fc2)+b_fc2)

#交叉熵
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels = y, logits=prediction))
#优化
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)

#结果
correct_prediction = tf.equal(tf.argmax(prediction,1),tf.argmax(y,1))
#准确率
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    for epoch in range(21):
        for batch in range(n_batch):
            batch_xs, batch_ys = mnist.train.next_batch(batch_size)
            sess.run(train_step, feed_dict={x:batch_xs, y:batch_ys, keep_prob:0.7})
        acc= sess.run(accuracy, feed_dict={x:mnist.test.images,y:mnist.test.labels, keep_prob:1.0})
        print("在第"+str(epoch)+"轮,准确率为"+str(acc))

classification


# Youku video tutorial: http://i.youku.com/pythontutorial

"""
Please note, this code is only for python 3+. If you are using python 2+, please modify the code accordingly.
"""
from __future__ import print_function
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# number 1 to 10 data
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)

def add_layer(inputs, in_size, out_size, activation_function=None,):
    # add one more layer and return the output of this layer
    Weights = tf.Variable(tf.random_normal([in_size, out_size]))
    biases = tf.Variable(tf.zeros([1, out_size]) + 0.1,)
    Wx_plus_b = tf.matmul(inputs, Weights) + biases
    if activation_function is None:
        outputs = Wx_plus_b
    else:
        outputs = activation_function(Wx_plus_b,)
    return outputs

def compute_accuracy(v_xs, v_ys):
    global prediction
    y_pre = sess.run(prediction, feed_dict={xs: v_xs})
    correct_prediction = tf.equal(tf.argmax(y_pre,1), tf.argmax(v_ys,1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
    result = sess.run(accuracy, feed_dict={xs: v_xs, ys: v_ys})
    return result

# define placeholder for inputs to network
xs = tf.placeholder(tf.float32, [None, 784]) # 28x28
ys = tf.placeholder(tf.float32, [None, 10])

# add output layer
prediction = add_layer(xs, 784, 10,  activation_function=tf.nn.softmax)

# the error between prediction and real data
cross_entropy = tf.reduce_mean(-tf.reduce_sum(ys * tf.log(prediction),
                                              reduction_indices=[1]))       # loss
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)

sess = tf.Session()
# important step
# tf.initialize_all_variables() no long valid from
# 2017-03-02 if using tensorflow >= 0.12
if int((tf.__version__).split('.')[1]) < 12 and int((tf.__version__).split('.')[0]) < 1:
    init = tf.initialize_all_variables()
else:
    init = tf.global_variables_initializer()
sess.run(init)

for i in range(1000):
    batch_xs, batch_ys = mnist.train.next_batch(100)
    sess.run(train_step, feed_dict={xs: batch_xs, ys: batch_ys})
    if i % 50 == 0:
        print(compute_accuracy(
            mnist.test.images, mnist.test.labels))


optimizer varialbe (with error)

# View more python learning tutorial on my Youtube and Youku channel!!!

# Youtube video tutorial: https://www.youtube.com/channel/UCdyjiB5H8Pu7aDTNVXTTpcg
# Youku video tutorial: http://i.youku.com/pythontutorial

"""
Please note, this code is only for python 3+. If you are using python 2+, please modify the code accordingly.
"""
from __future__ import print_function
import tensorflow as tf
import numpy as np


def add_layer(inputs, in_size, out_size, n_layer, activation_function=None):
    # add one more layer and return the output of this layer
    layer_name = 'layer%s' % n_layer
    with tf.name_scope(layer_name):
        with tf.name_scope('weights'):
            Weights = tf.Variable(tf.random_normal([in_size, out_size]), name='W')
            tf.summary.histogram(layer_name + '/weights', Weights)
        with tf.name_scope('biases'):
            biases = tf.Variable(tf.zeros([1, out_size]) + 0.1, name='b')
            tf.summary.histogram(layer_name + '/biases', biases)
        with tf.name_scope('Wx_plus_b'):
            Wx_plus_b = tf.add(tf.matmul(inputs, Weights), biases)
        if activation_function is None:
            outputs = Wx_plus_b
        else:
            outputs = activation_function(Wx_plus_b, )
        tf.summary.histogram(layer_name + '/outputs', outputs)
    return outputs


# Make up some real data
x_data = np.linspace(-1, 1, 300)[:, np.newaxis]
noise = np.random.normal(0, 0.05, x_data.shape)
y_data = np.square(x_data) - 0.5 + noise

# define placeholder for inputs to network
with tf.name_scope('inputs'):
    xs = tf.placeholder(tf.float32, [None, 1], name='x_input')
    ys = tf.placeholder(tf.float32, [None, 1], name='y_input')

# add hidden layer
l1 = add_layer(xs, 1, 10, n_layer=1, activation_function=tf.nn.relu)
# add output layer
prediction = add_layer(l1, 10, 1, n_layer=2, activation_function=None)

# the error between prediciton and real data
with tf.name_scope('loss'):
    loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction),
                                        reduction_indices=[1]))
    tf.summary.scalar('loss', loss)

with tf.name_scope('train'):
    train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)

sess = tf.Session()
merged = tf.summary.merge_all()

writer = tf.summary.FileWriter("logs/", sess.graph)

init = tf.global_variables_initializer()
sess.run(init)

for i in range(1000):
    sess.run(train_step, feed_dict={xs: x_data, ys: y_data})
    if i % 50 == 0:
        result = sess.run(merged,
                          feed_dict={xs: x_data, ys: y_data})
        writer.add_summary(result, i)

# direct to the local dir and run this in terminal:
# $ tensorboard --logdir logs


dropout

import tensorflow as tf
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data
#载入数据集
mnist= input_data.read_data_sets('MNIST_data', one_hot = True)

#设定每个批次的大小
batch_size = 100
#计算总共的批次
n_batch = mnist.train.num_examples//batch_size

x = tf.placeholder(tf.float32,[None,784])
y = tf.placeholder(tf.float32,[None,10])
keep_prob = tf.placeholder(tf.float32)
#构建神经网络
W = tf.Variable(tf.truncated_normal([784,2000], stddev = 0.1))
B = tf.Variable(tf.zeros([2000])+0.1)
p1 = tf.nn.softmax(tf.matmul(x,W)+B)
p1_dropout = tf.nn.dropout(p1,keep_prob)

W1 = tf.Variable(tf.truncated_normal([2000,2000]))
B1 = tf.Variable(tf.zeros([2000])+0.1)
p2 = tf.nn.softmax(tf.matmul(p1_dropout,W1)+B1)
p2_dropout = tf.nn.dropout(p2,keep_prob)

W2 = tf.Variable(tf.truncated_normal([2000,10]))
B2 = tf.Variable(tf.zeros([10])+0.1)
prediction = tf.nn.softmax(tf.matmul(p2_dropout,W2)+B2)

#定义二次代价函数
#loss = tf.reduce_mean(tf.square(y-prediction))
#重新定义对数(交叉熵)
loss =tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=prediction))
#使用梯度下降法
train_step = tf.train.GradientDescentOptimizer(0.2).minimize(loss)

#初始化
init = tf.global_variables_initializer()

#测试准确率
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(prediction,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))

#训练开始
with tf.Session() as sess:
    sess.run(init)
    for epoch in range(21):
        for batch in range(n_batch):
            batch_xs, batch_ys = mnist.train.next_batch(batch_size)
            sess.run(train_step, feed_dict={x:batch_xs, y:batch_ys,keep_prob:1.0})

        test_acc = sess.run(accuracy,feed_dict={x:mnist.test.images, y:mnist.test.labels, keep_prob:1.0})
        train_acc = sess.run(accuracy,feed_dict={x:mnist.train.images, y:mnist.train.labels, keep_prob:1.0})
        print("准确率为: 在"+str(epoch)+"回,"+str(test_acc)+", 但是在训练集中为"+str(train_acc))


number identification

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
#载入数据集
mnist= input_data.read_data_sets('MNIST_data', one_hot = True)

#设定每个批次的大小
batch_size = 100
#计算总共的批次
n_batch = mnist.train.num_examples // batch_size

x = tf.placeholder(tf.float32,[None,784])
y = tf.placeholder(tf.float32,[None,10])
keep_prob = tf.placeholder(tf.float32)
lr= tf.Variable(0.001,dtype=tf.float32)
#构建神经网络

# W = tf.Variable(tf.truncated_normal([784,10]))
# B = tf.Variable(tf.zeros([10])+0.1)
# prediction = tf.nn.softmax(tf.matmul(x,W)+B)

# W = tf.Variable(tf.zeros([784,10]))
# B = tf.Variable(tf.zeros([10]))
# prediction = tf.nn.softmax(tf.matmul(x,W)+B)

#构建神经网络
W = tf.Variable(tf.truncated_normal([784,500],stddev =0.1))
B = tf.Variable(tf.zeros([500])+0.1)
p1 = tf.nn.tanh(tf.matmul(x,W)+B)
p1_dropout = tf.nn.dropout(p1,keep_prob)

W1 = tf.Variable(tf.truncated_normal([500,200],stddev=0.1))
B1 = tf.Variable(tf.zeros([200])+0.1)
p2 = tf.nn.tanh(tf.matmul(p1_dropout,W1)+B1)
p2_dropout = tf.nn.dropout(p2,keep_prob)

W2 = tf.Variable(tf.truncated_normal([200,10],stddev = 0.1))
B2 = tf.Variable(tf.zeros([10])+0.1)
prediction = tf.nn.softmax(tf.matmul(p2_dropout,W2)+B2)



#定义二次代价函数
#loss = tf.reduce_mean(tf.square(y-prediction))
#重新定义对数(交叉熵)
loss =tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=prediction))
#使用梯度下降法
#train_step = tf.train.GradientDescentOptimizer(0.2).minimize(loss)
train_step = tf.train.AdamOptimizer(lr).minimize(loss)
#初始化
init = tf.global_variables_initializer()

#测试准确率
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(prediction,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))

# #训练开始
# with tf.Session() as sess:
#     sess.run(init)
#     for epoch in range(20):
#         for batch in range(n_batch):
#             batch_xs, batch_ys = mnist.train.next_batch(batch_size)
#             sess.run(train_step, feed_dict={x:batch_xs, y:batch_ys})
#         acc = sess.run(accuracy,feed_dict={x:mnist.test.images, y:mnist.test.labels})
#         print("准确率为: 在"+str(epoch)+"回,"+str(acc))


#训练开始
with tf.Session() as sess:
    sess.run(init)
    for epoch in range(41):
        sess.run(tf.assign(lr,0.001*(0.95**epoch)))
        for batch in range(n_batch):
            batch_xs, batch_ys = mnist.train.next_batch(batch_size)
            sess.run(train_step, feed_dict={x:batch_xs, y:batch_ys,keep_prob:1.0})
        learing_rate = sess.run(lr)
        test_acc = sess.run(accuracy,feed_dict={x:mnist.test.images,
y:mnist.test.labels, keep_prob:1.0})
        train_acc = sess.run(accuracy,feed_dict={x:mnist.train.images,
y:mnist.train.labels, keep_prob:1.0})
        print("准确率为: 在"+str(epoch)+"回,"+str(test_acc)+",但是在训练集中为"+str(train_acc)+"同时学习率为"+str(learing_rate))


with L regularizer


import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
BATCH_SIZE = 30
seed = 2
rdm = np.random.RandomState(seed)
X = rdm.randn(300,2)
Y_ = [int(x0*x0 + x1*x1 < 2) for (x0,x1) in X]
Y_c = [['red' if y else 'blue'] for y in Y_]
X = np.vstack(X).reshape(-1,2)
Y_ = np.vstack(Y_).reshape(-1,1)
print(X)
print(Y_)
print(Y_c)
plt.scatter(X[:,0],X[:,1], c = np.squeeze(Y_c))
plt.show()

def get_weight(shape, regularizer):
    w = tf.Variable(tf.random_normal(shape), dtype = tf.float32)
    tf.add_to_collection('losses', tf.contrib.layers.l2_regularizer(regularizer)(w))
    return w
def get_bias(shape):
    b = tf.Variable(tf.constant(0.01, shape=shape))
    return b
x = tf.placeholder(tf.float32, shape=(None, 2))
y_ = tf.placeholder(tf.float32, shape = (None , 1))
w1 = get_weight([2,11], 0.01)
b1 = get_bias([11])
y1 = tf.nn.relu(tf.matmul(x,w1)+b1)
w2 = get_weight([11,1],0.01)
b2 = get_bias([1])
y = tf.matmul(y1,w2)+b2

loss_mse = tf.reduce_mean(tf.square(y-y_))
loss_total = loss_mse + tf.add_n(tf.get_collection('losses'))


train_step_l = tf.train.AdamOptimizer(0.0001).minimize(loss_total)
with tf.Session() as sess:
    init_op = tf.global_variables_initializer()
    sess.run(init_op)
    STEPS = 40000
    for i in range(STEPS):
        start = (i*BATCH_SIZE) % 300
        end = start + BATCH_SIZE
        sess.run(train_step_l, feed_dict = {x:X[start:end], y_:Y_[start:end]})
        if i % 2000 == 0:
            loss_total_v = sess.run(loss_total, feed_dict={x:X,y_:Y_})
            print('After %d steps, loss is: %f' %(i, loss_total_v))
    xx, yy = np.mgrid[-3:3:0.01, -3:3:0.01]
    grid = np.c_[xx.ravel(), yy.ravel()]
    probs = sess.run(y, feed_dict={x:grid})
    probs = probs.reshape(xx.shape)
    print ('w1 is \n:', sess.run(w1))
    print ('b1 is \n:', sess.run(b1))
    print ('w2 is \n:', sess.run(w2))
    print ('b2 is \n:', sess.run(b2))
plt.scatter(X[:,0], X[:,1], c = np.squeeze(Y_c))
plt.contour(xx, yy, probs, levels = [.5])
plt.show()


print('loss_mse_v * loss_total_v is :', loss_mse_v*loss_total_v)


without L regularizer

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
BATCH_SIZE = 30
seed = 2
rdm = np.random.RandomState(seed)
X = rdm.randn(300,2)
Y_ = [int(x0*x0 + x1*x1 < 2) for (x0,x1) in X]
Y_c = [['red' if y else 'blue'] for y in Y_]
X = np.vstack(X).reshape(-1,2)
Y_ = np.vstack(Y_).reshape(-1,1)
print(X)
print(Y_)
print(Y_c)
plt.scatter(X[:,0],X[:,1], c = np.squeeze(Y_c))
plt.show()

def get_weight(shape, regularizer):
    w = tf.Variable(tf.random_normal(shape), dtype = tf.float32)
    tf.add_to_collection('losses', tf.contrib.layers.l2_regularizer(regularizer)(w))
    return w
def get_bias(shape):
    b = tf.Variable(tf.constant(0.01, shape=shape))
    return b
x = tf.placeholder(tf.float32, shape=(None, 2))
y_ = tf.placeholder(tf.float32, shape = (None , 1))
w1 = get_weight([2,11], 0.01)
b1 = get_bias([11])
y1 = tf.nn.relu(tf.matmul(x,w1)+b1)
w2 = get_weight([11,1],0.01)
b2 = get_bias([1])
y = tf.matmul(y1,w2)+b2

loss_mse = tf.reduce_mean(tf.square(y-y_))
loss_total = loss_mse + tf.add_n(tf.get_collection('losses'))

train_step = tf.train.AdamOptimizer(0.0001).minimize(loss_mse)
with tf.Session() as sess:
    init_op = tf.global_variables_initializer()
    sess.run(init_op)
    STEPS = 40000
    for i in range(STEPS):
        start = (i*BATCH_SIZE) % 300
        end = start + BATCH_SIZE
        sess.run(train_step, feed_dict = {x:X[start:end], y_:Y_[start:end]})
        if i % 2000 == 0:
            loss_mse_v = sess.run(loss_mse, feed_dict={x:X,y_:Y_})
            print('After %d steps, loss is: %f' %(i, loss_mse_v))
    xx, yy = np.mgrid[-3:3:0.01, -3:3:0.01]
    grid = np.c_[xx.ravel(), yy.ravel()]
    probs = sess.run(y, feed_dict={x:grid})
    probs = probs.reshape(xx.shape)
    print ('w1 is \n:', sess.run(w1))
    print ('b1 is \n:', sess.run(b1))
    print ('w2 is \n:', sess.run(w2))
    print ('b2 is \n:', sess.run(b2))
plt.scatter(X[:,0], X[:,1], c = np.squeeze(Y_c))
plt.contour(xx, yy, probs, levels = [.5])
plt.show()


exponen decay with L regularizer(this has error)

import numpy as np
import matplotlib.pyplot as plt


try:
    import opt4_8_generateds
    import opt4_8_forward
except:
    import pip 
    pip.main(['install','opt4_8_forward'])
    pip.main(['install','opt4_8_generateds'])
    import opt4_8_generateds
    import opt4_8_forward



STEPS = 40000
BATCH_SIZE = 30
LEARNING_RATE_BASE = 0.001
LEARNING_RATE_DECAY = 0.999
REGULARIZER = 0.01

def backward():
    x = tf.placeholder(tf.float32, shape = (None,2))
    y_ = tf.placeholder(tf.float32, shape = (None,1))

    x , Y_, Y_c = opt4_8_generateds.generateds()
    y = opt4_8_forward.forward(x,REGULARIZER)

    global_steps = tf.Variable(0, trainable= False)
    learning_rate = tf.train.exponential_decay(
        LEARNING_RATE_BASE,
        global_steps,
        300/BATCH_SIZE,
        LEARNING_RATE_DECAY,
        staircase = True)
    loss_mse = tf.reduce_mean(tf.square(y-y_))
    loss_total = loss_mse + tf.add_n(tf.get_collection('losses'))

    train_step = tf.train.AdamOptimizer(learning_rate).minimizer(loss_total)

    with tf.Session() as sess:
        init_op = tf.global_variables_initializer()
        sess.run(init_op)
        for i in range(STEPS):
            start = (i*BATCH_SIZE) % 300
            end = start + BATCH_SIZE
            sess.run(train_step, feed_dict = {x:X[start:end], y_:Y_[start:end]})
            if i % 2000 == 0:
                loss_v = sess.run(loss_total, feed_dict={x:X,y_:Y_})
                print('After %d steps, loss is: %f' %(i, loss_v))
        xx, yy = np.mgrid[-3:3:0.01, -3:3:0.01]
        grid = np.c_[xx.ravel(), yy.ravel()]
        probs = sess.run(y, feed_dict={x:grid})
        probs = probs.reshape(xx.shape)

    plt.scatter(X[:,0], X[:,1], c = np.squeeze(Y_c))
    plt.contour(xx, yy, probs, levels = [.5])
    plt.show()

if __name__ == '__main__':
    backward()


read date for variables

from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('./data', one_hot = True)

# print(mnist.train.labels[0])
# print(mnist.train.images[0])

BATCH_SIZE = 200
xs, ys = mnist.train.next_batch(BATCH_SIZE)
print("xs shape :", xs.shape)
print("ys shape :", ys.shape)


#+startup: content

keras

classification



# please note, all tutorial code are running under python3.5.
# If you use the version like python2.7, please modify the code accordingly

# 5 - Classifier example

import numpy as np
np.random.seed(1337)  # for reproducibility
from keras.datasets import mnist
from keras.utils import np_utils
from keras.models import Sequential
from keras.layers import Dense, Activation
from keras.optimizers import RMSprop

# download the mnist to the path '~/.keras/datasets/' if it is the first time to be called
# X shape (60,000 28x28), y shape (10,000, )
(X_train, y_train), (X_test, y_test) = mnist.load_data()

# data pre-processing
X_train = X_train.reshape(X_train.shape[0], -1) / 255.   # normalize
X_test = X_test.reshape(X_test.shape[0], -1) / 255.      # normalize
y_train = np_utils.to_categorical(y_train, num_classes=10)
y_test = np_utils.to_categorical(y_test, num_classes=10)

# Another way to build your neural net
model = Sequential([
    Dense(32, input_dim=784),
    Activation('relu'),
    Dense(10),
    Activation('softmax'),
])

# Another way to define your optimizer
rmsprop = RMSprop(lr=0.001, rho=0.9, epsilon=1e-08, decay=0.0)

# We add metrics to get more results you want to see
model.compile(optimizer=rmsprop,
              loss='categorical_crossentropy',
              metrics=['accuracy'])

print('Training ------------')
# Another way to train the model
model.fit(X_train, y_train, epochs=2, batch_size=32)

print('\nTesting ------------')
# Evaluate the model with the metrics we defined earlier
loss, accuracy = model.evaluate(X_test, y_test)

print('test loss: ', loss)
print('test accuracy: ', accuracy)

regression

# # please note, all tutorial code are running under python3.5.
# # If you use the version like python2.7, please modify the code accordingly

# # 4 - Regressor example

import numpy as np
np.random.seed(1337)  # for reproducibility
from keras.models import Sequential
from keras.layers import Dense
import matplotlib.pyplot as plt

# create some data
X = np.linspace(-1, 1, 200)
np.random.shuffle(X)    # randomize the data
Y = 0.5 * X + 2 + np.random.normal(0, 0.05, (200 ))
# plot data
plt.scatter(X, Y)
plt.show()

X_train, Y_train = X[:160], Y[:160]     # first 160 data points
X_test, Y_test = X[160:], Y[160:]       # last 40 data points

# build a neural network from the 1st layer to the last layer
model = Sequential()

model.add(Dense(units=1, input_dim=1)) 

# choose loss function and optimizing method
model.compile(loss='mse', optimizer='sgd')

# training
print('Training -----------')
for step in range(301):
    cost = model.train_on_batch(X_train, Y_train)
    if step % 100 == 0:
        print('train cost: ', cost)

# test
print('\nTesting ------------')
cost = model.evaluate(X_test, Y_test, batch_size=40)
print('test cost:', cost)
W, b = model.layers[0].get_weights()
print('Weights=', W, '\nbiases=', b)

# plotting the prediction
Y_pred = model.predict(X_test)
plt.scatter(X_test, Y_test)
plt.plot(X_test, Y_pred)
plt.show()

sklearn

decisiontree

from sklearn.feature_extraction import DictVectorizer
import csv
from sklearn import preprocessing
from sklearn import tree
from sklearn.externals.six import StringIO
import numpy as np
import pandas as pd
from pylab import *

allElectronicsData = open("computer.csv")
reader = csv.reader(allElectronicsData)
headers = next(reader)
print(headers)
print(reader)

featureList = []
labelList = []
for row in reader:
    labelList.append(row[len(row)-1])
    rowDict = {}
    for i in range(1,len(row)-1):
        rowDict[headers[i]] = row[i]
    featureList.append(rowDict)
print(featureList)

vec = DictVectorizer()
dummyX = vec.fit_transform(featureList).toarray()
print("dummyX: " + str(dummyX))
print(vec.get_feature_names())

print("labeList" + str(labelList))
lb = preprocessing.LabelBinarizer()
dummyY = lb.fit_transform(labelList)
print("dummyY:" + str(dummyY))

clf = tree.DecisionTreeClassifier(criterion= 'entropy')
clf = clf.fit(dummyX,dummyY)
print("clf :" + str(clf))

# save as dot
with open("output.dot","w") as f:
    f = tree.export_graphviz(clf, feature_names= vec.get_feature_names(), out_file = f)

#in terminnal gives the flowwing comands

#    dot -Tpdf -O output.dot
#    xdg-open output.pdf

cross validation 1

# View more python learning tutorial on my Youtube and Youku channel!!!

# Youtube video tutorial: https://www.youtube.com/channel/UCdyjiB5H8Pu7aDTNVXTTpcg
# Youku video tutorial: http://i.youku.com/pythontutorial

"""
Please note, this code is only for python 3+. If you are using python 2+, please modify the code accordingly.
"""
from __future__ import print_function
from sklearn.datasets import load_iris
from sklearn.cross_validation import train_test_split
from sklearn.neighbors import KNeighborsClassifier

iris = load_iris()
X = iris.data
y = iris.target

# test train split #
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=4)
knn = KNeighborsClassifier(n_neighbors=5)
knn.fit(X_train, y_train)
y_pred = knn.predict(X_test)
print(knn.score(X_test, y_test))

# this is cross_val_score #
from sklearn.cross_validation import cross_val_score
knn = KNeighborsClassifier(n_neighbors=5)
scores = cross_val_score(knn, X, y, cv=5, scoring='accuracy')
print(scores)

# this is how to use cross_val_score to choose model and configs #
from sklearn.cross_validation import cross_val_score
import matplotlib.pyplot as plt
k_range = range(1, 31)
k_scores = []
for k in k_range:
    knn = KNeighborsClassifier(n_neighbors=k)
    loss = -cross_val_score(knn, X, y, cv=10, scoring='mean_squared_error') # for regression
    k_scores.append(loss.mean())

plt.plot(k_range, k_scores)
plt.xlabel('Value of K for KNN')
plt.ylabel('Cross-Validated Accuracy')
plt.show()


cross validation 2

# View more python learning tutorial on my Youtube and Youku channel!!!

# Youtube video tutorial: https://www.youtube.com/channel/UCdyjiB5H8Pu7aDTNVXTTpcg
# Youku video tutorial: http://i.youku.com/pythontutorial

"""
Please note, this code is only for python 3+. If you are using python 2+, please modify the code accordingly.
"""
from __future__ import print_function
from sklearn.learning_curve import  learning_curve
from sklearn.datasets import load_digits
from sklearn.svm import SVC
import matplotlib.pyplot as plt
import numpy as np

digits = load_digits()
X = digits.data
y = digits.target
train_sizes, train_loss, test_loss= learning_curve(
        SVC(gamma=0.01), X, y, cv=10, scoring='mean_squared_error',
        train_sizes=[0.1, 0.25, 0.5, 0.75, 1])
train_loss_mean = -np.mean(train_loss, axis=1)
test_loss_mean = -np.mean(test_loss, axis=1)

plt.plot(train_sizes, train_loss_mean, 'o-', color="r",
             label="Training")
plt.plot(train_sizes, test_loss_mean, 'o-', color="g",
             label="Cross-validation")

plt.xlabel("Training examples")
plt.ylabel("Loss")
plt.legend(loc="best")
plt.show()


corss validation 3

# View more python learning tutorial on my Youtube and Youku channel!!!

# Youtube video tutorial: https://www.youtube.com/channel/UCdyjiB5H8Pu7aDTNVXTTpcg
# Youku video tutorial: http://i.youku.com/pythontutorial

"""
Please note, this code is only for python 3+. If you are using python 2+, please modify the code accordingly.
"""
from __future__ import print_function
from sklearn.learning_curve import  validation_curve
from sklearn.datasets import load_digits
from sklearn.svm import SVC
import matplotlib.pyplot as plt
import numpy as np

digits = load_digits()
X = digits.data
y = digits.target
param_range = np.logspace(-6, -2.3, 5)
train_loss, test_loss = validation_curve(
        SVC(), X, y, param_name='gamma', param_range=param_range, cv=10,
        scoring='mean_squared_error')
train_loss_mean = -np.mean(train_loss, axis=1)
test_loss_mean = -np.mean(test_loss, axis=1)

plt.plot(param_range, train_loss_mean, 'o-', color="r",
             label="Training")
plt.plot(param_range, test_loss_mean, 'o-', color="g",
             label="Cross-validation")

plt.xlabel("gamma")
plt.ylabel("Loss")
plt.legend(loc="best")
plt.show()


data application

# View more python learning tutorial on my Youtube and Youku channel!!!

# Youtube video tutorial: https://www.youtube.com/channel/UCdyjiB5H8Pu7aDTNVXTTpcg
# Youku video tutorial: http://i.youku.com/pythontutorial

"""
Please note, this code is only for python 3+. If you are using python 2+, please modify the code accordingly.
"""
from __future__ import print_function
from sklearn import datasets
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt

loaded_data = datasets.load_boston()
data_X = loaded_data.data
data_y = loaded_data.target

model = LinearRegression()
model.fit(data_X, data_y)

print(model.predict(data_X[:4, :]))
print(data_y[:4])

X, y = datasets.make_regression(n_samples=100, n_features=1, n_targets=1, noise=1)
plt.scatter(X, y)
plt.show()


eigenschaft function

# View more python learning tutorial on my Youtube and Youku channel!!!

# Youtube video tutorial: https://www.youtube.com/channel/UCdyjiB5H8Pu7aDTNVXTTpcg
# Youku video tutorial: http://i.youku.com/pythontutorial

"""
Please note, this code is only for python 3+. If you are using python 2+, please modify the code accordingly.
"""
from __future__ import print_function
from sklearn import datasets
from sklearn.linear_model import LinearRegression

loaded_data = datasets.load_boston()
data_X = loaded_data.data
data_y = loaded_data.target

model = LinearRegression()
model.fit(data_X, data_y)

print(model.predict(data_X[:4, :]))
print(model.coef_)
print(model.intercept_)
print(model.get_params())
print(model.score(data_X, data_y)) # R^2 coefficient of determination


iris

View more python learning tutorial on my Youtube and Youku channel!!!

Youtube video tutorial: https://www.youtube.com/channel/UCdyjiB5H8Pu7aDTNVXTTpcg Youku video tutorial: http://i.youku.com/pythontutorial


"""
Please note, this code is only for python 3+. If you are using python 2+, please modify the code accordingly.
"""
from __future__ import print_function
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier

iris = datasets.load_iris()
iris_X = iris.data
iris_y = iris.target


X_train, X_test, y_train, y_test = train_test_split(
    iris_X, iris_y, test_size=0.3)


knn = KNeighborsClassifier()
knn.fit(X_train, y_train)
print(knn.predict(X_test))
print(y_test)


normnalization

# View more python learning tutorial on my Youtube and Youku channel!!!

# Youtube video tutorial: https://www.youtube.com/channel/UCdyjiB5H8Pu7aDTNVXTTpcg
# Youku video tutorial: http://i.youku.com/pythontutorial

"""
Please note, this code is only for python 3+. If you are using python 2+, please modify the code accordingly.
"""
from __future__ import print_function
from sklearn import preprocessing
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.datasets.samples_generator import make_classification
from sklearn.svm import SVC
import matplotlib.pyplot as plt

a = np.array([[10, 2.7, 3.6],
                     [-100, 5, -2],
                     [120, 20, 40]], dtype=np.float64)
print(a)
print(preprocessing.scale(a))

X, y = make_classification(n_samples=300, n_features=2 , n_redundant=0, n_informative=2, random_state=22, n_clusters_per_class=1, scale=100)
plt.scatter(X[:, 0], X[:, 1], c=y)
plt.show()
X = preprocessing.scale(X)    # normalization step
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.3)
clf = SVC()
clf.fit(X_train, y_train)
print(clf.score(X_test, y_test))


save load

# View more python tutorials on my Youtube and Youku channel!!!

# Youtube video tutorial: https://www.youtube.com/channel/UCdyjiB5H8Pu7aDTNVXTTpcg
# Youku video tutorial: http://i.youku.com/pythontutorial

"""
Please note, this code is only for python 3+. If you are using python 2+, please modify the code accordingly.
"""
from __future__ import print_function
from sklearn import svm
from sklearn import datasets

clf = svm.SVC()
iris = datasets.load_iris()
X, y = iris.data, iris.target
clf.fit(X, y)

# # method 1: pickle
# import pickle
# # save
# with open('save/clf.pickle', 'wb') as f:
#     pickle.dump(clf, f)
# # restore
# with open('save/clf.pickle', 'rb') as f:
#    clf2 = pickle.load(f)
#    print(clf2.predict(X[0:1]))

# method 2: joblib
from sklearn.externals import joblib
# Save
joblib.dump(clf, 'save/clf.pkl')
# restore
clf3 = joblib.load('save/clf.pkl')
print(clf3.predict(X[0:1]))


theano

basic

# View more python tutorials on my Youtube and Youku channel!!!

# Youtube video tutorial: https://www.youtube.com/channel/UCdyjiB5H8Pu7aDTNVXTTpcg
# Youku video tutorial: http://i.youku.com/pythontutorial

# 4 - basic usage
#   from __future__ import print_function
import numpy as np
import theano.tensor as T
from theano import function

# basic
x = T.dscalar('x')
y = T.dscalar('y')
z = x+y     # define the actual function in here
f = function([x, y], z)  # the inputs are in [], and the output in the "z"

print(f(2,3))  # only give the inputs "x and y" for this function, then it will calculate the output "z"

# # to pretty-print the function
from theano import pp
print(pp(z))

# # how about matrix
x = T.dmatrix('x')
y = T.dmatrix('y')
z = x + y
f = function([x, y], z)
print(f(np.arange(12).reshape((3,4)), 10*np.ones((3,4))))


Tensorflow 2

Tensorflow foundation

数值类型


type diam shape function Scalar 0 [] acc Vector 1 [n,] bias (b) Matrix 2 [n, m] weight (W) Tensor lg 3 [n,m,p] input ( [n, h, w, 3]



a = tf.constant(example)
tf.constant()  # 功能类似于tf.convert_to_tensor()
b = tf.constant('Hello Deep learning')
c = tf.constant(True)
dtype=tf.int16, int32, int64,tf.float16, tf.float32, tf.float64
tf.cast(a, tf.float64)
tf.Variable(a)    #可以添加a的可训练属性
tf.zeros([n,m])  tf.zeros_like(a)  == tf.zeros(a.shape)
tf.ones([n,m])   tf.ones_like(a)   == tf.ones(a.shape)
tf.fill([2,2],10)
tf.random.normal([2,2]) == tf.random.normal([2,2], mean=0, stddev=1)
tf.random.uniform(shape, minval=0,maxval=10,dtype=tf.float32)
tf.range(10) == tf.range(0,10, delta = 2)

Reference(,) and Segment(:)

x = tf.random.normal([4,32,32,3])
x[2][1][0][1]  == x[2,1,0,1]

[start:end:step] for each dimension.
x[1:3:2, 1:4:2, 2:4:2, 1:3:2]

改变视图

x = tf.random.normal([4,32,32,3]) 的数据是整体贮存的,可以合法的 reshape. 从后往前合并,拆分。

  1. 增加维度

    增加前置维度 tf.expand~dims~(x, axis=0) 增加后置维度 tf.expand~dims~(x, axis=-1) 也可以是其他值,表示在相应的位置增加一个维度

  2. 删除维度

    删除前置 tf.squeeze(x, axis=0) 后置和其他位置一样,删除dia=1的维度

交换维度

这会改变数据的贮存顺序 x = tf.random.normal([2,32,32,3]) x = tf.transpose(x, perm=[0,3,1,2]) 以前的维度下表变换为perm

Broadcasting

tile

x = tf.random.normal([4,32,32,3]) y = tf.tile(x,[2,3,3,1]) 对应维度各复制成原来的2,3,3,1倍。

Concatenate & Stack & Split & unstack

tf.concat([a,b],axis=0) 除了axis=0外的所有维度都应该一样 tf.stack([a,b],axis=0) a,b的所有维度应该都一样,插入的位置和 expand~dims~() 遵守相同规则 tf.split(x, num~orsizesplits~=10, axis=0) 拆分的维度不消失 tf.unstack(x, axis=0) 拆为步长为1 拆分的维度消失

Statistik

L1 Norm tf.norm(x, ord=1) L2 Norm tf.norm(x,ord=2)

tf.reduce~max~(x, axis=0) tf.reduce~min~() tf.reduce~mean~() tf.reduce~sum~() 不指明axis则是对全局求解 tf.argmax(x, axis) tf.argmin(x,axis) axis 轴的极值坐标


out = tf.random.normal([100,10])
out = tf.nn.softmax(out, axis=1)
pred = tf.argmax(out, axis=1)
y = tf.random.uniform([100],dtype=tf.int64,maxval=10)
out = tf.equal(pred, y)
out = tf.cast(out, dtype=tf.float32)
cor = tf.reduce_sum(out)

Padding

x = tf.pad(x,[[0,2]]) []内是padding 填充的方案,每个[]表示一个维度

advance manipulation

tf.minimum

tf.minimum(x, a) 最小a tf.maximum(x, b) 最大b tf.minimum(tf.maximum(x,2),7) == tf.clip~byvalue~(x,2,7)

tf.gather

tf.gather(x, [0,2,4,5,7],axis =1) 抽取在axis=1上的[0,2,4,5,7]坐标的组 成数据,并可以重新定义组成数据的顺序

tf.gather~nd~

后面根的[]说明了所有成员要操作的维度, 第一成员的第一维坐标为1,第二维坐标为1.. 所有成员组成List

tf.boolean~mask~

tf.boolean~mask~(x, mask=[True, False, True, False],axis =0) 在axis=0的轴上,只有mask成员是True才会被选中,mask 长度等于axis=0 轴的 长度。

tf.where

a = tf.ones([3,3])
b = tf.zeros([3,3])
cond = tf.constant([True,False,False],[False, True, True],[False, False, False])
c = tf.where(cond, a,b)

tf.where(cond) 返回所有值为True元素的下标

x = tf.random.normal([3.3])
mask = x>0
ind = tf.where(mask)
a = tf.gather_nd(x,ind)

tf.scatter~nd~

在一个长度为8的空白向量(全为0)里,将updates按照indices的位置写入

indices = tf.constant([[4],[3],[2],[1]])
updates = tf.constant([3,1,0,2])
tf.scatter_nd(indices, updates, [8])

tf.meshgrid

x = tf.linspace(-8., 8, 100)   #-8后面的. 不能省略
y = tf.linspace(-8., 8, 100)
x.shape = 100
x, y = tf.meshgrid(x,y)
x.shape = [100,100]
ax.contour3D(x.numpy(), y.numpy(), z.numpy(), 50)

chapter 01 code

一个很简单的例子,用tf来求某个函数的导数

import tensorflow as tf
a = tf.constant(1.)
b = tf.constant(2.)
c = tf.constant(3.)
w = tf.constant(4.)

with tf.GradientTape() as tape:
    tape.watch([w])
    y = a*w**2 + b*w + c
[dy_dw] = tape.gradient(y, [w])
print(dy_dw)

检测cpu和gpu运行时的时间对比

import tensorflow as tf
import timeit

n = 10000000
with tf.device('/cpu:0'):
    cpu_a = tf.random.normal([1, n])
    cpu_b = tf.random.normal([n, 1])

with tf.device('/gpu:0'):
    gpu_a = tf.random.normal([1, n])
    gpu_b = tf.random.normal([n, 1])

def cpu_run():
    with tf.device('/cpu:0'):
        c = tf.matmul(cpu_a, cpu_b)
    return c

def gpu_run():
    with tf.device('/gpu:0'):
        c = tf.matmul(gpu_a, cpu_b)
    return c

cpu_time = timeit.timeit(cpu_run, number=10)
gpu_time = timeit.timeit(cpu_run, number=10)
print('run time: ', cpu_time, gpu_time)



不用tensorflow的API,使用纯函数来实现神经网络训练的例子

import numpy as np
data = []
for i in range(100):
    x = np.random.uniform(-10., 10)
    y = 1.477*x + 0.089 + np.random.normal(0., 0.01)
    data.append([x, y])
data = np.array(data)


def mse(b, w, points):
    totalError = 0
    for i in range(0, len(points)):
        x = points[i, 0]
        y = points[i, 1]
        totalError += (y-(w*x+b))**2
    return totalError/float(len(points))


def step_gradient(b_current, w_current, points, lr):
    b_gradient = 0
    w_gradient = 0
    M = float(len(points))
    for i in range(0, len(points)):
        x = points[i, 0]
        y = points[i, 1]
        b_gradient += (2/M)*((w_current*x+b_current)-y)
        w_gradient += (2/M)*x*((w_current*x + b_current)-y)
    new_b = b_current - (lr*b_gradient)
    new_w = w_current - (lr*w_gradient)
    return [new_b, new_w]


def gradient_descent(points, staring_b, staring_w, lr, num_iterations):
    b = staring_b
    w = staring_w
    for step in range(num_iterations):
        b, w = step_gradient(b, w, np.array(points), lr)
        loss = mse(b, w, points)
        if step % 5000  == 0:
            print(f"iterations:{step}, loss :{loss}, w:{w}, b:{b}")
    return [b, w]


def main():
    lr = 0.001
    initial_b = 0
    initial_w = 0
    num_iterations = 100000
    [b, w] = gradient_descent(data, initial_b, initial_w, lr, num_iterations)
    loss = mse(b, w, data)
    print(f"Final loss :{loss}, w:{w}, b:{b}")


# if __name__ ==' __main__':
main()


MNIST dataset

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers, optimizers, datasets
w1 = tf.Variable(tf.random.truncated_normal([784, 256], stddev=0.1))
b1 = tf.Variable(tf.zeros([256]))
w2 = tf.Variable(tf.random.truncated_normal([256, 128], stddev=0.1))
b2 = tf.Variable(tf.zeros([128]))
w3 = tf.Variable(tf.random.truncated_normal([128, 10], stddev=0.1))
b3 = tf.Variable(tf.zeros([10]))
(x,y),(x_val, y_val)=datasets.mnist.load_data()
print('x:',x.shape, 'y:', y.shape,'x test:', x_val.shape, 'y test:', y_val)
def preprocess(x, y):
    x = tf.cast(x, dtype = tf.float32)/255.
    x = tf.reshape(x, [-1,28*28])
    y = tf.cast(y,dtype=tf.int32)
    y = tf.one_hot(y, depth=10)
    return x,y
train_db = tf.data.Dataset.from_tensor_slices((x,y))  #构建Dataset 对象
train_db = train_db.shuffle(10000)                    # 打散样本顺序
train_db = train_db.batch(128)                        #批训练
train_db = train_db.map(preprocess)
test_db = tf.data.Dataset.from_tensor_slices((x_val, y_val))
test_db = test_db.shuffle(1000)
test_db = test_db.batch(128)
test_db = test_db.map(preprocess)
lr = 0.001
for epoch in range(8):
    for step, (x,y) in enumerate(train_db):
        with tf.GradientTape() as tape:
            h1 = x@w1 + tf.broadcast_to(b1, [x.shape[0], 256])
            h1 = tf.nn.relu(h1)
            h2 = h1@w2 + b2
            h2 = tf.nn.relu(h2)
            out = h2@w3 + b3
            loss = tf.square(y - out)
            loss = tf.reduce_mean(loss)
            grads = tape.gradient(loss, [w1,b1,w2,b2,w3,b3])
            w1.assign_sub(lr *grads[0])
            b1.assign_sub(lr * grads[1])
            w2.assign_sub(lr *grads[2])
            b2.assign_sub(lr * grads[3])
            w3.assign_sub(lr *grads[4])
            b3.assign_sub(lr * grads[5])
for x, y in test_db:
    h1 = x@w1 + b1
    h1 = tf.nn.relu(h1)
    h2 = h1@w2 + b2
    h2 = tf.nn.relu(h2)
    out = h2@w3 + b3
    pred = tf.argmax(out,axis=1)
    y = tf.argmax(y, axis=1)
    correct = tf.equal(pred, y)
    total_correct +=tf.reduce_sum(tf.cast(correct,dty=tf.int32)).numpy()



Make~moons~

all import

import seaborn as sns
import matplotlib.pyplot as plt

generate the data

from sklearn.datasets import make_moons
from sklearn.model_selection import train_test_split
N_samples = 2000
Test_size = 0.3
X, y = make_moons(n_samples = N_samples, noise = 0.2, random_state=100)
X_train, X_test, y_train, y_test = train_test_split(X, y,test_size = Test_size, random_state = 42)
print(X.shape, y.shape)
def make_plot(X, y, plot_name, file_name=None, XX=None, YY=None, preds=None,dark=False):
    if(dark):
        plt.style.use('dark_background')
    else:
        sns.set_style("whitegrid")
    plt.figure(figsize=(16,12))
    axes = plt.gca()
    axes.set(xlabel="$x_1$", ylabel="$x_2$")
    plt.title(plot_name,fontsize=30)
    plt.subplots_adjust(left=0.20)
    plt.subplots_adjust(right=0.8)
    if(XX is not None and YY is not None and preds is not None):
        plt.contourf(XX,YY,preds.reshape(XX.shape), 25, alpha=1,cmap = cm.Spectral)
        plt.contour(XX,YY, preds.reshape(XX.shape), levels=[.5],cmap="Greys", vmin=0,vmax=0.6)
        plt.scatter(X[:,0],X[:,1],c=y.ravel(), s=40, cmap=plt.cm.Spectral,edgecolors='none')
        plt.savefig('data.svg')
        plt.close()
make_plot(X,y,None,"Classification Dataset Visualization")

generate the signal Layer class

class Layer:
    def __init__(self, n_input, n_neurons,activation=None, weight=None,bias=None):
        self.weight = weight if weight is not None else np.random.randn(n_input,n_neurons)*np.sqrt(1/n_neurons)
        self.bias = bias if bias is not None else np.random.rand(n_neurons)*0.1
        self.activation = activation
        self.last_activation = None
        self.error = None
        self.delta = None
    def activate(self,x):
        r = np.dot(x, self.weight)+self.bias
        self.last_activation = self._apply_activation(r)
        return self.last_activation
    def _apply_activation(self, r):
        if self.activation is None:
            return r
        elif self.activation == 'relu':
            return np.maximum(r,0)
        elif self.activation == 'tanh':
            return np.tanh(r)
        elif self.activation == 'sigmoid':
            return 1/(1+np.exp(-r))
        return r
    def apply_activation_derivative(self, r):
        if self.activation is None:
            return np.ones_like(r)
        elif self.activation == 'relu':
            grad = np.array(r, copy=True)
            grad[r>0] = 1.
            grad[r<=0] =0.
            return grad
        elif self.activation == 'tanh':
            return 1-r**2
        elif self.activation == 'sigmoid':
            return r*(1-r)
        return r

generate the multi Layers Class NeuralNetwork

class NeuralNetwork:
    def __init__(self):
        self._layers = []
    def add_layer(self, layer):
        self._layers.append(layer)
    def feed_forward(self, X):
        for layer in self._layers:
            X = layer.activate(X)
        return X

    def backpropagation(self, X, y,learning_rate):
        output = self.feed_forward(X)
        for i in reversed(range(len(self._layers))):
            layer = self._layers[i]
            if layer == self._layers[-1]:
                layer.error = y-output
                layer.delta = layer.error*layer.apply_activation_derivative(output)
            else:
                next_layer = self._layers[i+1]
                layer.error = np.dot(next_layer.weights, next_layer.delta)
                layer.delta = layer.error*layer.apply_activation_derivative(layer.last_activation)

        for i in range(len(self._layers)):
            layer = self._layers[i]
            o_i = np.atleast_2d(X if i == 0 else  self._layers[i-1].last_activation)
            layer.weights += layer.delta*o_i.T*learning_rate


    def train(self, X_train, X_test, y_train, y_test, learning_rate, max_epochs):
        y_onehot = np.zeros((y_train.shape[0],2))
        y_onehot[np.arange(y_train.shape[0]),y_train] =1
        mses = []
        for i in range(max_epochs):
            for j in range(len(X_train)):
                self.backpropagation(X_train[j], y_onehot[j], learning_rate)
            if i%10 == 0:
                mse = np.mean(np.square(y_onehot - self.feed_forward(X_train)))
                mses.apply(mse)
                print('Epoch : #%s, MSE: %f' %(i, float(mse)))
                print('Accuracy: %.2f%%' %(self.accuracy(self.predict(X_test),y_test.flatten())*100))
        return mses


nn = Neuralnetwork()
nn.add_layer(Layer (2, 25, 'sigmoid'))
nn.add_layer(Layer(25, 50, 'sigmoid'))
nn.add_layer(Layer(50, 25, 'sigmoid'))
nn.add_layer(Layer(25, 2, 'sigmoid'))
nn.backpropagation(X_train,y_train,0.001)
nn.train(X_train, X_test, y_train, y_test, 0.001,20)


different Layers

for n in range(5):
    model = Sequential()
    model.add(Dense(8,input_dim=2,activation='relu'))
    for _ in range(n):
        model.add(Dense(32,activation='relu'))
    model.add(Dense(1,activation='sigmoid'))
    model.compile(loss='binary_crossentropy',optimizer='adam',metrics=['accuracy'])
    history = model.fit(X_train,y_train,epochs = 20, verbose=1)
    preds = model.predict_classes(np.c_[XX.ravel(), YY_ravel()])
    title = "网络层数({})".format(n)
    file = "网络容量 %f.png" %(2+n*1)
    make_plot(X_train,y_train, title,file,XX,YY,preds)


Keras

tf.keras

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers

x = tf.constant([2., 1., 0.1])
print(tf.keras.layers.Softmax(axis=-1)(x))
print(tf.nn.softmax(x))

tf.keras.Model 是tf.keras.Sequential的父类(网络类) Sequential类还有方法: Sequential.compile() Sequential.fit() Sequential.predict()

tf.keras.layers.Layer 是网络层类的父类(网络层类)

模型的保存和加载

  1. 保存数值

    Sequential.save~weights~('weights.ckpt') 重建了一样的网络后,重新加载 Sequential.load~weights~('weights.ckpt')

  2. 保存框架

    tf.keras.Sequential.save('model.h5') 不需要重构模型,可以直接生成保存的模型 network = tf.keras.models.load~model~('model.h5')

  3. 跨系统平台保存恢复

    tf.saved~model~.save(network, 'model-savedmodel') 复制,分发该文件后,在跨平台上复现 network = tf.saved~model~.load('model-savedmodel')

self-def

自定义网络层类,继承Layer 自定义网络类,继承Model

Dropout

tf.nn.dropout(x, rate = 0.5) model.add(layers.Dropout(rate=0.5))

Data Augmentation

resize

tf.image.resize(x,[244,244])

rote

tf.image.rot90(x,1) k为1时,代表一个90度的g逆时针旋转

flip

tf.image.random~flipleftright~(x) tf.image.random~flipupdown~(x)

crop

先放大,再剪裁 tf.image.resize(x,[244,244]) tf.image.random~crop~(x,[224,224,3])

IDE

emacs

Pycharm


M-1 open projects C-M-c collapse 折叠代码 C-M-e expand 打开代码 C-M-s open Settings C-S-+ increasing fonts C-S+- decreasing fonts C-S-0 reset fonts S-Esc close S-tab open in Emacs S-Enter execute/run C-S-i go to define file C-M-l show line C-F12 close main bar C-M-x exit C-A-[] change in between opened projects C-ins in project add a new file C-c C-p execute python file C-c C-o close (python) tab f11 Full screen A-. open the relate source file


jupyter

sudo apt install jupyter
sudo apt install jupyter lab
pip install jupyterthemes
jt -t monokai -f fira -fs 13 -nf ptsans -nfs 11 -N -kl -cursw 5 -cursc r -cellw 95% -T

Helf -> edit shortcut


j next cell k previous cell f pull the cell to the top i intercept cell c clear results space next site ctrl space previous site ctrl enter execute and to the next cell C-M-m close mainbar C-M-n close toolbar


Flask

open development and debug mode

export FLASK_APP=app
export FLASK_DEBUG=1
export FLASK_ENV=development
flask run

Django

deployment

  • null=True if allow this to be empty in the input interface
  • blank=True if it's empty from the interface, if set it to be NULL(not good for strings filed)

Golab notebook with Vim

  1. Cell model


    j/k C-n/C-p Cell之间上下移动 Enter to normal model or insert model


  2. Normal Model


    M-n/M-p Cell 之间上下移动 Markdown 双击右边的视图回到Cell model Code 点击左边执行框内阴影回到Cell model i to insert model


  3. Insert model


    Up/Down 行之间上下移动 C-Left/C-right 词语之间左右移动 M-Up/M-Down 行的上下互换 Markdown 双击右边的视图回到Cell model Code 点击左边执行框内阴影回到Cell model



w next word front b previous word front e end of word i insert front word I insert front line a insert end word A insert end line o insert line up O insert line down u redo x delete char y copy yy copy line d delete dd delete line p pasta gg document begin G document end


test

import os
os.system("ls -l")

Exception

def example1():
    print("example 01")
    try:
        a = 10 / 0
    except ZeroDivisionError as e:
        print("catched")
        raise RuntimeError("Runtime error") from e
    except Exception as e:
        print(e.__class__.__name__)

def call():
    try:
        example1()
    except RuntimeError as e:
        print(e.__class__.__name__)
        print(e.args)
        print("Runtime Error")
    except Exception as e:
        print(e.__class__.__name__)
        print(e.args)

call()

.env not be share


title: Emacs

#+STARTUP: content

customize

helps

C-h v comands
customize the settings
C-M-\ zusammen runs the command indent-region (ESC C-\ getrennt)
C-h c runs the command describe-key-briefly
C-j runs the command org-return-and-maybe-indent
C-q runs the command quoted-insert
C-d runs the command org-delete-char
M-DEL (translated from <M-backspace>) runs the command backward-kill-word
M eqaul to C-u

bookmark

C-x r m bookmarks set


C-x r b bookmark jump

configuration with packages

how to extension the packages from someone already wrote

M-x load file ~/.emacs.d/packages/echo-keys.el
M-x echo-keys-mode
(global-set-key "\C-o" 'compile)
(global-set-key "\C-\M-r" 'ranger)

file control dired & treemacs

mode dired


enter or a or f enter the file c or C-o other buffer view + creat a directory m mark C copy to R rename or move D delete


mode treemacs

this can be another helpful control tool, ? for help


C-M-r treemacs open folder ? help
M-o to treemacs from file to treemacs


Virtual environment

在terminal 打开虚拟环境后,在打开 Emacs Emacs 会继承这些环境变量

shortcut Emacsclient

emacsclient -a "" -c

hotkey setting

M-x: global-set-key Press the wanted keybindings input the mapped command

(global-set-key "\C-o" 'compile)

chinese fonts


M-x install cnfonts 安装 (require 'cnfonts) enable config M-x cnfonts-edit-profile config (cnfonts-enable) load from start M-x cnfonts-set-font-with-saved-step 手动加载 M-x cnfonts-decrease-fontsize 增大整个系统的字体大小 M-x cnfonts-increase-fontsize 减小


daemon process

alias emc="emacsclient -c "

emacs --daemon
emc xxx.org

error

if by configuration failed, emacs --debug-init find the postion M-x: goto-char postion

EMACS Commands

commands functions explain


C-c C-p call the functions execute buffer for language (python) C-c C-c execute programm or function watch out the execute envirment C-c C-o open website link links or website both C-c C-w save as 另存为 C-u C-x C-e execute expression force the results show where the cursor it C-M-x open shell M-x term C-M-SPC mark the word the whole worlds M-x customize-option Word-wrap ON, 关掉换行

Timer

commands functions expression


C-c C-x 0 start the timer from 00:00:00 C-c C-x - print the time how long has been start C-c C-x , pause or continue one pause, one continue C-u C-c C-x , stop clear all

Extension

Yasnippes

first make sure wich mode you are, so the new setting can only be used in the same mode, and the mode must be save in this mode

M-x yas-new-snippes

mu4e


mu4e open mail client A e 1 & 1 view attachments C-c C-a add attachment g 2 go to the second link


eww

q :for quit w(eww-copy-page-url) :copy the URL

d (eww-download) g (eww-reload) l(eww-back-url) :previous seit r(eww-forward-url) :forward seit

b(eww-add-bookmark) : add current seit as bookmark B(eww-list-bookmarks) : view bookmark

S(eww-list-buffers) s(eww-switch-to-buffer)

& (eww-browse-with-external-browser) eww-use-external-browser-for-content-type v (eww-view-source)

C (url-cookie-list)

helpful mode for edit

M-x linum mode
M-x check parens
M-x show-parent-mode  (Error :end file of parsing) can be caused by lack of parentheses

Rectangle


add content for all select lines string-insert-rectangle add content for all select lines string-rectangle cut content for all select mark region C-x SPE C-w post content for all select mark region C-x SPE C-y


Org mode

rich text

| Great clouds overhead | Tiny black birds rise and fall | Snow covers Emacs | |    ---AlexSchroeder

Everything should be made as simple as possible, but not any simpler ---Albert Einstein

::: CENTER Everything should be made as simple as possible,
but not any simpler :::

here I will try some nows, and this is to be funny, and [underlined]{.underline}.

commods


org mode manual in emccs M-x org-info C-x C-q enable readonly C-; 可以检查当前单词的拼写 sudo apt install grip, M-x grip mode live compile for markdown C-c C-z add note to items, quick note C-c C-c switch between them


checklist

可以在item后面加上[0/2] or [0%]

  • S-A-Ent for a new checklist
  • C-c C-c to finish this checklist

commands function explain


C-c C-o goto the link must in the link description C-c C-l edit the link also in the link C-c C-. go back

mark the link in file


* headline #+NAME: target []{#target} #+alias #+title org-store-link

use the mark, which is marked

[[.../file.org::345]] go to the file of line 345
[[.../file.org::target]] to to the file with target, 3 kinds of internal
[[file:~/code/main.c::255  ]]               进入到 255 行
[[file:~/xx.org::My Target ]]                   找到目标‘<<My Target>>’
[[file:~/xx.org::#my-custom-id]]               查找自定义 id 的项

org-insert-link

org-msg

- mbsync setting seeing in Dropbox
- C-c C-m to send email
- math :file output.png -> C-c C-c
- digraph ->
- graph --

org-noter

M-x: package install : org-noter
- open xxx.pdf as emacs
- M-x: org-noter -> create a file as assige its position(a image without type name will be created)
- i for generic notes, M-i for special note with mouse to click
- give name and make notes
- C-M- (. p n) check notes for current, previous, and after notes 
with a rot arrow to the file

org-reveal reveal.js & ox-reveal

need to download reveal-js(unzip, and path pass to org-reveal-root) reveal.js download need to download org-reveal(were replace by ox-reveal) org reveal ox reveal

#+OPTIONS: num:nil toc:nil
#+REVEAL_TRANS: None/Fade/Slide/Convex/Concave/Zoom
#+REVEAL_THEME: Black/White/League/Sky/Beige/Simple/Serif/Blood/Night/Moon/Solarized
#+Title: Title of Your Talk
#+Author: Your Name
#+Email: Your Email Address or Twitter Handle

org-html-themes

org-html-themes github

add this at the top 
#+SETUPFILE: https://fniessen.github.io/org-html-themes/setup/theme-readtheorg.setup

或者下载后用本地的模板

# -*- mode: org; -*-

#+HTML_HEAD: <link rel="stylesheet" type="text/css" href="/home/sx/Dropbox/Sprache/Emacs/orgmode/org-html-themes/styles/readtheorg/css/htmlize.css"/>
#+HTML_HEAD: <link rel="stylesheet" type="text/css" href="/home/sx/Dropbox/Sprache/Emacs/orgmode/org-html-themes/styles/readtheorg/css/readtheorg.css"/>

#+HTML_HEAD: <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
#+HTML_HEAD: <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
#+HTML_HEAD: <script type="text/javascript" src="/home/sx/Dropbox/Sprache/Emacs/orgmode/org-html-themes/styles/lib/js/jquery.stickytableheaders.min.js"></script>
#+HTML_HEAD: <script type="text/javascript" src="/home/sx/Dropbox/Sprache/Emacs/orgmode/org-html-themes/styles/readtheorg/js/readtheorg.js"></script>

org-mind-map

github link is here,

M-x org-mind-map-write to execute

add legend, text display, image display

org-roam

org-roam-mode org-roam-db-build-cache org-roam-find-index org-roam-find-file org-roam-insert

org-journal

[]{#quickstart}


M-x org-journal-mode activate the mode C-c C-j(org-journal-new-entry) create one, can be today, can be in the futher C-u C-c C-j go to the current entry C-c C-t add TODO C-c C-d add deadline C-c a a view in agenda


lsp-java

lsp-java github.io

dap-java github.io

lsp-java github

dap-java github

lsp-java-generate-getters-and-setters 需要安装helm 在所有的可选中 C-SPE 选中


helm

for C-x C-f :find files C-l go back to the above directory

(helm-mode 1)
(require 'helm-config)
(global-set-key (kbd "M-x") 'helm-M-x)
(global-set-key (kbd "M-y") 'helm-show-kill-ring)
(global-set-key (kbd "C-x C-f") 'helm-find-files)

helm-org-rifle

在已经打开的所有文件中匹配搜索关键词,是所有打开文件
keywords searching in all opened files, external files,

tree graph

(graph-draw-binary-tree '(1 (2 (3) (4)) (5)))
(graph-draw-tree '((north-america (usa
                                    (miami)
                                    (seattle)
                                    (idaho (boise))))
                   (europe (germany)
                            (france (paris)
                                     (lyon)
                                     (cannes)))))

ox-beamer

for images see hpc report

SRC block

commands


<s Tab old version (require 'org-tempo) new version executable C-c C-, new version C-c C-x C-v view png of latex in SRC C-c C-x C-l view image of latex in pure orgmode C-c ' edit all src in a new buffer with mode


options

src 前缀


#+name: blockname blockname 可以被:noweb yes的代码块调用 #+call :blockname(x = 3)
#+PROPERTY: tangle xxx.tex 全文所有相关码块导出到xxx.tex文件 #+PROPERTY: comments org 全文org格式内容(不在src块中)导出时被注释


src 后缀


language function C/python/emacs-lisp
:file abc.org
:dir 指定生成代码的路径 :results output
:export (到html文件) code 只导出代码,results 只是结果 ,both :session my 可切换到生成的my buffer 操作 :tangle (创建源码) 文件名,yes, no :noweb yes 对tangle和export作用 :tangle xxx.py 输出文件 :var x=2
:shebang 指定码块的解释器


noweb:可以使用任何设定了名字的代码块,每次都是重新执行一遍所有相关代码。 session:后台会启动一个相应的解释器控制台,所有名称相同的代码块都会被加 载到该控制台,一直运行,并可以交互。

ditaa

sudo apt-get install ditaa C-c C-x C-v to view

+---------+
|         |
| 1       |
|         |
+----+----+---+
|222 |233     |
|    |        |
+----+--------+

+------+   +-----+   +-----+   +-----+
|{io}  |   |{d}  |   |{s}  |   |cBLU |
| 2oo  +---+ Bar +---+ Baz +---+ Moo |
|      |   |     |   |     |   |     |
+------+   +-----+   +--+--+   +-----+
                        |
           /-----\      |      +------+
           |     |      |      | c1AB |
           | Goo +------+---=--+ Sh12 |
           \-----/             |      |
                               +------+

graphviz

sudo apt install graphviz

  digraph diagramm {
          MG [shape= box,color = red]
          MG1 [shape=box,color=red]        
          lambdaL1 [color=red]
          ROOT [shape=diamond]
          ROOT2 [shape=diamond]

          mh2 -> MG;
          mh3 -> MG;
          lambdaL1->MG;
          MG -> cs1[label = "pp>h2h2j"];
          cs1 -> ROOT[label = "w"];
          MG -> data_file;
          data_file -> Events_file [label = "1"];
          Events_file -> ROOT;
          ROOT -> sigma1;
          sigma1 -> lambdaL2[label = "2"];
          lambdaL2 -> MG1;  
          MG1->cs2;
          cs2 -> ROOT2[label = "w"];
          MG1 -> data_file_1;
          data_file_1 -> ROOT2 [label = "1"];
          ROOT2 -> sigma2;
          sigma2 -> lambdaL;

}

math

equation

\hat{f}(x) & \propto & \sum_{\nu} \frac{|F(\nu)H(\nu)|^2}{|N(\nu)|^2}
\frac{G(\nu)}{H(\nu)} e^{\frac{2 \pi i \nu x}{N}}\ & \propto & \sum_{\nu} \frac{|F(\nu)|^2}{|N(\nu)|^2} H(\nu) H^(\nu) \frac{G(\nu)}{H(\nu)} e^{\frac{2 \pi i \nu x}{N}}\ & \propto & \sum_{\nu} H^(\nu) G(\nu) e^{\frac{2 \pi i \nu x}{N}}

\begin{eqnarray*}
\hat{f}(x) & \propto & \sum_{\nu} \frac{|F(\nu)H(\nu)|^2}{|N(\nu)|^2}  
           \frac{G(\nu)}{H(\nu)} e^{\frac{2 \pi i \nu x}{N}}\\
           & \propto & \sum_{\nu} \frac{|F(\nu)|^2}{|N(\nu)|^2} H(\nu) H^*(\nu) 
           \frac{G(\nu)}{H(\nu)} e^{\frac{2 \pi i \nu x}{N}}\\
           & \propto & \sum_{\nu} H^*(\nu) G(\nu) e^{\frac{2 \pi i \nu x}{N}}
\end{eqnarray*}

Maxwell's Equations

\begin{align}
\nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\partial t} & = \frac{4\pi}{c}\vec{\mathbf{j}} \\
\nabla \cdot \vec{\mathbf{E}} & = 4 \pi \rho \\
\nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} & = \vec{\mathbf{0}} \\
\nabla \cdot \vec{\mathbf{B}} & = 0
\end{align}

Matrix

\begin{equation}
    s_{kk'}=
    \left(
    \begin{array}{ccc}
            h_{1k} &
            \cdots &
            h_{nk}
    \end{array}
    \right)
    \left(
    \begin{array}{ccc}
            \bar{q}_{11} & \cdots & \bar{q}_{12}\\
            \vdots & \ddots & \vdots\\
            \bar{q}_{n1} & \cdots & \bar{q}_{n2}
    \end{array}
    \right)
    \left(
    \begin{array}{c}
            h_{1k'} \\
            \vdots \\
            h_{nk'}
   \end{array}
   \right)
  \end{equation}
\begin{matrix} 0 & 1 \\ 1 & 0 \end{matrix}
\begin{pmatrix} 0 & 1 \\ 1 & 0 \end{pmatrix}
\begin{bmatrix} 0 & 1 \\ 1 & 0 \end{bmatrix}
\begin{Bmatrix} 0 & 1 \\ 1 & 0 \end{Bmatrix}
\begin{vmatrix} 0 & 1 \\ 1 & 0 \end{vmatrix}
\begin{Vmatrix} 0 & 1 \\ 1 & 0 \end{Vmatrix}

symbolic math

If and , then the solution must be either or .

parentheses

set

Tabelle

\begin{table}[htbp]
\centering
\begin{tabular}{|c|c|c|}
Überschrift 1 & Überschrift 2 & berschrift 3 \\
\hline
Eins & Zwei & Drei \\
Vier & Fünf & Sechs \\
\end{tabular}
\caption[Tabelle]{Tolle Tabelle}
\label{tab:toll1}
\end{table}

Special characters

 latex-math-preview-insert-mathematical-symbol
this is to add special characters for latex

Formation

添加大括号

\begin{cases}
\end{cases}

增加分行

\begin{aligned}
\end{aligned}

在orgmode中,Esc下面的~键可以调出希腊字母输入 C-z也可以调出特殊字符输入

<span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6833em;"></span><span class="mord mathcal">L</span></span></span></span>
<span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6833em;"></span><span class="mord mathcal" style="margin-right:0.03041em;">B</span></span></span></span>

Compile Python2

1. in Orgmode using SRC to save a python2 programm, with its interpreter
2. C-c ' opening the buffer
3. C-c C-p open the python interpreter, weather it is wanted
4. mark the region in programm buffer
5. C-c C-r import the marked region to the interpreter

Agenda & capture & todo

comands explain function


C-c c add new capture capture C-c C-s 1 add new scheduling to items agenda C-c C-t 2 add new TODO to items todo C-c C-d add new deadline to items agenda C-c a check agenda function agenda C-c a a check all agenda items f, b S-f from capture list to file agenda C-' 3 switch in all agenda file agenda C-c C-x C-c view todo, pri and tags of items summary C-c C-c(q) add tags in items must in items

ispell-region

mark all the region I want to check, and M-X ispell-region space for nothing and numbers for replace.

notebook-jupyter

conda activate tf emacs xxx.ipynb C-c C-o

official link document emacs ipython notebook github link

Install

M-x package-refresh-contents RET M-x package-install RET ein RET

emacs xxx.ipynb C-c C-l/o

commands


C-c C-a ein:worksheet-insert-cell-above-km 向上插入cell C-c C-b ein:worksheet-insert-cell-below-km 向下插入cell C-c C-c ein:worksheet-execute-cell-km 执行cell C-c C-k ein:worksheet-kill-cell-km kill cell C-c C-s ein:worksheet-split-cell-at-point-km 划分cell C-c C-w ein:worksheet-copy-cell-km 复制cell C-c C-l ein:worksheet-clear-output-km 清除结果 C-c C-u ein:worksheet-change-cell-type-km 更换属性cell C-c C-z ein:notebook-kernel-interrupt-command-km 中断cell C-c C-y ein:worksheet-yank-cell-km yank cell C-c RET ein:worksheet-merge-cell-km 向上融合cell C-c C-f ein:file-open-km 打开文件 C-c C-p ein:worksheet-goto-next-input-km previous(<C-down>) C-c C-n ein:worksheet-goto-prev-input-km Next (<C-up>) M-Ent ein:worksheet-execute-cell-and-goto-next-km execute, goto next



C-u C-c C-c ein:worksheet-execute-all-cells C-c C-e ein:worksheet-toggle-output-km C-c C-n ein:worksheet-goto-next-input-km C-c C-o ein:notebook-open-km C-c C-p ein:worksheet-goto-prev-input-km C-c C-q ein:notebook-kill-kernel-then-close-command-km C-c C-r ein:notebook-reconnect-session-command-km C-c C-t ein:worksheet-toggle-cell-type-km C-c C-v ein:worksheet-set-output-visibility-all-km C-c C-x Prefix Command


1

在任何的item上,C-c C-s都可以增加scheduling,可以个性的指定加入的 日期和时间。如果该item有TODO 特性,增加 ++1w 在时间后面,可以多次更新

2

在上次更新的-State "DONE"之前加上本次的完成情况,然后不管TODO 的标签是什么,C-c C-t d (done), 该item的scheduling将会被自动更新到下 一次的设定时间(一周后)。在时间轴上显示历次完成情况.

3

shift + f can dynamical view the agenda items. and Tab goto the linked agenda file.


title: Haskell

#+startup:  content

commands

in file.hs

C-c C-l to execute file.hs and go to interactive environment Seeing ./black.hs

C-c C-c call in src

log2 :: Float -> Float
  log2 = logBase 2
  log2 43

with :results value :eval (inferior-haskell-start-process)

in src can multi functions be defined. and the last call will be printed

with follow extension, can be easy C-c C-c executed, but not in send to haskell log file, but only output the last result

Seeing Literatur Programm Grundlage

send to haskell/org-src-block

log2 :: Float -> Float
  log2 = logBase 2
  log2 43

#+end_src

first to load file. ~/.emacs.d/packages/orgmode-babal-haskell.el in one of src block M-x : send to haskell/org-src-block

in src block without any extension can be load in send buffer(after src haskell), and the be called function can be many type.

important : in src block the calling syntax is NOT allowed

Seeing Literatur Programm Alternativen

Functional Programm

Grundlage

basic function call

log2 :: Float -> Float
  log2 = logBase 2
  log2 43

implication

(==>):: Bool -> Bool -> Bool
a ==> b = not a || not b
Flase ==> True
False==> False
True ==> True

--euler numbers

e:: Float
e = exp 1
e 

Pattern Matching

one of the calling must match one case of pattern

(<#>) :: Bool -> Bool -> Bool
  (<#>) False False = False
  (<#>) False True = True
  (<#>) True False = True
  (<#>) True True = True


True <#> True

(<#>) :: Bool -> Bool -> Bool
  (<#>) True True = True
  (<#>) _ _ = False

(<#>) True True
(<#>) False True

(<#>) :: Bool -> Bool -> Bool
  (<#>) True True 

case : this can only be executed in a .hs file, in orgmode can NOT be imported, I don't know what is going on in Terminal can NOT also

Here I made above mistake, this is no sense. so long the indentation is correct, so works

(<#>) :: Bool -> Bool -> Bool
(<#>) a b
  | a == b = False
  | otherwise = True


Alternativen

if else then

absolute :: Int -> Int
absolute x = if x < 0 then -x else x

Recursion

easy fib

heronA ::(Int, Double) -> Double
heronA (n,a)
  | n > 0     = (heronA(n-1,a) + a/heronA(n-1, a))/2
  | otherwise = a

absolute :: Int -> Int
absolute x = if x < 0 then -x else x

heronB :: Int -> Double -> Double
heronB n a
  | n > 0     = (heronB (n-1) a + a/heronB(n-1) a)/2
  | otherwise = a

where

heronC :: Int -> Double -> Double
heronC n a
  |n > 0      = (x + a/x)/2
  |otherwise  = a
  where x = heronC (n-1) a

fib & where

fibA :: Int -> Int
fibA n
  |n == 0    = 0
  |n == 1    = 1
  |otherwise = x +y
  where
    x = fibA (n-1)
    y = fibA (n-2)

fib & where & pattern matching

fibB :: Int -> Int
fibB 0 = 0
fibB 1 = 1
fibB n = fibB (n-1) + fibB (n-2)


fibC :: Int -> Int
fibC 0 = 0
fibC 1 = 1
fibC n
  | n < 0      = error "illegal arguement"
  | otherwise  = fibB (n-1) + fibB (n-2)


(<##>) :: Int -> Double -> Double
0 <##> a   = a
n <##> a  
  | n > 0  = (x + a/x)/2
  | otherwise  = error "illegal arguement"
  where x = (n-1) <##> a

Type conversion1

Guides

vielleichtdreifach :: Bool -> Bool -> Integer -> Integer
vielleichtdreifach verdreifach nochmal n
  | verdreifach && nochmal = maldrei ( maldrei n)
  | verdreifach            = maldrei n
  | otherwise              = n
  where maldrei n = 3*n 

dreifach :: Integer -> Integer
dreifach = vielleichtdreifach True False 

neudreifach :: Integer -> Integer
neudreifach = vielleichtdreifach True True

vielleichtdreifach Bool Bool -> Integer

Factorial

fac :: Integer -> Integer
fac n
  | n == 0  = 1
  | otherwise = fac (n-1) * n

Stern Brocot Floge

(*/*) :: Integer -> Integer -> Integer
(*/*) = div

(*%*) :: Integer -> Integer -> Integer
(*%*) = rem

sternBrocot :: Integer -> Integer
sternBrocot n
  | n == 0      = 0
  | n == 1      = 1
  | n *%* 2 == 0 = sternBrocot half
  | otherwise    = sternBrocot half + sternBrocot (half + 1)
  where half = n */* 2

suche :: Integer -> Integer -> Integer
suche suchziel postionziel
  | sternBrocot postionziel > suchziel = postionziel
  | otherwise                          = suche suchziel (postionziel +1)

List

字符串就是单一字符的列表

List add

in prelude

[1,2,3] ++ [3,4,5]
2 : [3,4]

Symbol

需要时刻谨记是用 . 来做函数组合的,$ 是用来降低函数执行优先级的。

Functional Programm of Haskell

Grundlage

basic function call

  log2 :: Float -> Float
  log2 = logBase 2
log2 43

implication


(==>):: Bool -> Bool -> Bool
a ==> b = not a || not b
Flase ==> True
False==> False
True ==> True

--euler numbers


  e:: Float
    e = exp 1
e 

Pattern Matching

one of the calling must match one case of pattern

(<#>) :: Bool -> Bool -> Bool
  (<#>) False False = False
  (<#>) False True = True
  (<#>) True False = True
  (<#>) True True = True


True <#> True
(<#>) :: Bool -> Bool -> Bool
  (<#>) True True = True
  (<#>) _ _ = False

(<#>) True True
(<#>) False True

(<#>) :: Bool -> Bool -> Bool
  (<#>) True True = True

case : this can only be executed in a .hs file, in orgmode can NOT be imported, I don't know what is going on in Terminal can NOT also

Here I made above mistake, this is no sense. so long the indentation is correct, so works

(<#>) :: Bool -> Bool -> Bool
(<#>) a b
  | a == b = False
  | otherwise = True


Alternativen

if else then

absolute :: Int -> Int
absolute x = if x < 0 then -x else x

Recursion

easy fib

heronA ::(Int, Double) -> Double
heronA (n,a)
  | n > 0     = (heronA(n-1,a) + a/heronA(n-1, a))/2
  | otherwise = a

absolute :: Int -> Int
absolute x = if x < 0 then -x else x

heronB :: Int -> Double -> Double
heronB n a
  | n > 0     = (heronB (n-1) a + a/heronB(n-1) a)/2
  | otherwise = a

where

heronC :: Int -> Double -> Double
heronC n a
  |n > 0      = (x + a/x)/2
  |otherwise  = a
  where x = heronC (n-1) a

fib & where

fibA :: Int -> Int
fibA n
  |n == 0    = 0
  |n == 1    = 1
  |otherwise = x +y
  where
    x = fibA (n-1)
    y = fibA (n-2)

fib & where & pattern matching

fibB :: Int -> Int
fibB 0 = 0
fibB 1 = 1
fibB n = fibB (n-1) + fibB (n-2)


fibC :: Int -> Int
fibC 0 = 0
fibC 1 = 1
fibC n
  | n < 0      = error "illegal arguement"
  | otherwise  = fibB (n-1) + fibB (n-2)


(<##>) :: Int -> Double -> Double
0 <##> a   = a
n <##> a  
  | n > 0  = (x + a/x)/2
  | otherwise  = error "illegal arguement"
  where x = (n-1) <##> a

type conversion

Guides

vielleichtdreifach :: Bool -> Bool -> Integer -> Integer
vielleichtdreifach verdreifach nochmal n
  | verdreifach && nochmal = maldrei ( maldrei n)
  | verdreifach            = maldrei n
  | otherwise              = n
  where maldrei n = 3*n 

dreifach :: Integer -> Integer
dreifach = vielleichtdreifach True False 

neudreifach :: Integer -> Integer
neudreifach = vielleichtdreifach True True

vielleichtdreifach Bool Bool -> Integer

Factorial

fac :: Integer -> Integer
fac n
  | n == 0  = 1
  | otherwise = fac (n-1) * n

Stern Brocot Floge

(*/*) :: Integer -> Integer -> Integer
(*/*) = div

(*%*) :: Integer -> Integer -> Integer
(*%*) = rem

sternBrocot :: Integer -> Integer
sternBrocot n
  | n == 0      = 0
  | n == 1      = 1
  | n *%* 2 == 0 = sternBrocot half
  | otherwise    = sternBrocot half + sternBrocot (half + 1)
  where half = n */* 2

suche :: Integer -> Integer -> Integer
suche suchziel postionziel
  | sternBrocot postionziel > suchziel = postionziel
  | otherwise                          = suche suchziel (postionziel +1)


title: Julia

#+STARTUP: overview
println("KJI")

KJI

title: MySql

#+STARTUP: content

configuation

安装

install

sudo apt install mysql-server
sudo mysql_secure_installation

此时是给电脑的root用户,创建了一个mysql里root用户的数据库

电脑的root用户

sudo apt install mysql-server sudo mysql~secureinstallation~

sudo

上面默认设置的是电脑root用户的密码,也就是说只能 sudo 登陆 : sudo mysql -u root -p create new user 后可以用非sudo 登录

with password

关闭无密码登录

USE mysql;
UPDATE user SET plugin='mysql_native_password' WHERE User='root';
FLUSH PRIVILEGES;
exit;

sudo systemctl restart mysql.service sudo mysql~secureinstallation~

remote connect

sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf

bind-address = 127.0.0.1

Chinese

对该 my.ini 文件下进行配置修改 :

[client]
default-character-set = utf8

[mysql]
default-character-set = utf8

[mysqld]
character-set-client-handshake = FALSE
character-set-server = utf8
collation-server = utf8_unicode_ci
init_connect=’SET NAMES utf8’

Plugin is not loaded

if Plugin *** is not loaded: 修改mysql.cnf 在 [mysqld]下添加skip-grant-tables

电脑的普通用户进入配置 This is not needed


step env command explain 01 terminal sudo mysql -u root -p 电脑root进入mysql的root 02 mysql select User, Host, plugin from user; 获取 03 mysql update user set plugin='mysql_ native_ password';
04 mysql select User, Host, plugin from user; 获取 05 mysql flush privileges; 权限更新 in mysqld:skip-grant-tables 06 mysql 1 C-d C-d 退出 07 terminal mysql -u root BUT NOT (mysql -u root -p) 不能 -p, 密码为空,直接Enter进入 08 mysql set password for root@localhost = '123' 老版本 = password('123'); 09 error 123 is too simple, just not satisfy the check the password requirement. 10 mysql show variables like 'validate_ password%'; 显示密码设置要求 11 mysql set global validate_ password_ length=3; 设置密码长度要求 为 3 12 mysql set global validate_ password_ policy=0; 设置密码要求概要 为 0 13 mysql set password for root@localhost = '123' 老版本 = password('123'); 14 mysql flush privileges; 权限更新 in mysqld:skip-grant-tables 15 terminal mysql -u root -p 密码 123 , 登陆时不需要 sudo 开头


给数据库添加用户

在进入数据库的root后,mysql 添加普通用户 简书连接 .

create USER 'sx'@'localhost' IDENTIFIED BY 'scofild'; 创建sx用户,只能本地连接,秘密scofild

GRANT ALL ON testforjava.course TO 'sx'@'localhost'; 开放testforjava数据集中的course数据表的所有全线给sx 用户

退出后登陆 sx 用户 mysql -u sx -p scofild

便只能看到有权限的数据集

查看数据库及添加数据库

show databases;

create databese kurs;

drop databases kurs;

中文设置


show variables like 'character%';

听说mysql的utf8不是真的utf8,需要使用utf8mb4. 在用户登陆后用set charactater server database = utf8 或者utf8mb4, 只要重开接入,设置就复原。 只有在/etc/mysql/中的mysql.cnf中的clint/mysqld/mysql字段加入以上设定,重启生效


在[client]下追加 default-character-set=utf8 在[mysqld]下追加 character-set-server=utf8 在[mysql]下追加 default-character-set=utf8


特殊字符

  • 用`ry-vue`

create database `ry-vue`;

execute file 执行sql文件

mysql -u root -p xxxx use database; source .../file.sql

remote

alter user 'root'@'localhost' indentified by '110011';

reboot

sudo systemctl restart mysql

Operation

进入数据库

create databese testforjava; use testforjava;

插入表格

create table course(
       id int primary key atuo_increment,
       kurs_name varchar(50),
       kurs_length  varchar(50),
       teacher varchar(50),
       categeory varchar(50)
       );

for later version, only works for auto~increment~, not for identity(m,n)

插入值

insert into kurs values(1, 'C++', 23, 'su', 'basic'); insert into kurs values (2, 'Python', 50, 'morvan', 'hard'); insert into kurs values(3, 'CLI', 22, 'su', 'basic');

或者 不完整信息

insert into kurs(id, kurs~name~, categeory) values(4, 'java', 'basic'); (指定属性给值)

查看表格

show tables;

describe course;

编辑表格

alter table course rename kurs; (重命名)

alter table kurs add link varchar(50); (添加属性,列)

alter table kurs drop column link; (将该列删除)

alter table kurs modify teacher varchar(100); (修改该列的属性,增加容量)

alter table kurs change column teacher lecture varchar(100); (修改该列的名称,和属性,)

读取内容

select * from kurs;

select kurs~name~, lecture from kurs;

读取内容时,不重复显示

select distinct lecture from kurs;

高级条件查询

select * from course where course~name~ = 'gnome';

select * from course where course~length~ > 10;

select * from course where lecture='su' and categeory='adv'; (满足这两个要求的) select * from course order by course~length~ desc; (由课程长度有小到大排序) 后面加desc 则反序排序

delete

delete from course where id =2; delete from table where key=value

update

update course set lecture = 'Lee' where id =3;

backup

mysqldump -u root -p kurs > firstForFun.sql; (在root下将kurs数据库备份为FirstForFun.sql)

mysql -u root -p kurs < Firstforfun.sql (将备份文件FirstForFun.sql恢复为kurs数据库)

(此两个语句是在退出sql后的terminal执行的)

Management

user

show databases; use mysql; show tables;

mysqld --skip-grant-tables (开启mysql的无验证登陆,对于遗失密码后) select host,user from user; (查看所有用户)

create user 'cloud'@'%' identified by 'password'; drop user 'root'@'%';

rename user si to shi; (将si重命名为shi) set password = password('new'); (将当前用户密码改为new) set password for si = password(link); (将si用户密码重置为link)

grant all privileges on **.** to 'cloud'@'%' with grant option; flush privileges;

privileges

creat

create user shi identified by 'lining'; grant all privileges on **.** to 'shi'@'%' identified by 'lining' with grant option; flush privileges;

grant all privileges on **.** to 'root'@'%' identified by 'lining';

查询

show grants for 'newuser'@'localhost'

授予

grants 权限列表 on 数据库名.表明 to '用户'@'主机名' grants all on . 'newuser'@'localhost'

撤销

revoke delete on . from 'newuser'@'localhost'

timezone

set global time~zone~ = '+8:00'; ##修改mysql全局时区为北京时间,即我们所在的东8区 set time~zone~ = '+8:00'; ##修改当前会话时区 flush privileges; #立即生效

Operations for SQL

decripation

there can available code to execute, change the dbhost and dbpassword

check the connection in 0812erp

#+name: myweb
#+header: :engine mysql
#+header: :dbhost localhost
#+header: :dbuser cloud
#+header: :dbpassword "password"
#+header: :database 0812erp
show tables;
Tables_in_0812erp
bus_customer
bus_goods
bus_inport
bus_outport
bus_provider
bus_sales
bus_salesback
sys_dept
sys_loginfo
sys_menu
sys_notice
sys_role
sys_role_menu
sys_role_user
sys_user
#+header: :engine mysql
#+header: :dbhost localhost
#+header: :dbuser cloud
#+header: :dbpassword "password"
#+header: :database 0812erp
SELECT * FROM sys_menu          

check the database

#+name: my-query
#+header: :engine mysql
#+header: :dbhost localhost
#+header: :dbuser root
#+header: :dbpassword "123456"
#+header: :database testforjava
show tables;
#+RESULTS: my-query

dump database

mysqldump -uroot -p123456 testforjava > ~/Desktop/mysql.sql

delete database

#+name: my-query1
#+header: :engine mysql
#+header: :dbhost localhost
#+header: :dbuser root
#+header: :dbpassword "123456"
drop database testforjava;
show databases;

Database

information~schema~ 0812erp mysql performance~schema~ sys

recover testforjava

#+name: my-query2
#+header: :engine mysql
#+header: :dbhost localhost
#+header: :dbuser root
#+header: :dbpassword "123456"
create database testforjava;
use testforjava;
source ~/Desktop/mysql.sql
show databases;

Database

information~schema~ 0812erp mysql performance~schema~ sys testforjava

Table creation update delete

#+header: :engine mysql
#+header: :dbhost localhost
#+header: :dbuser cloud
#+header: :dbpassword "password"
#+header: :database tuto
-- 班级表
CREATE TABLE classe(
    id INT PRIMARY KEY auto_increment,
    caption VARCHAR(30) COMMENT '班级名'
);

-- 学生表
CREATE TABLE student(
    id INT UNSIGNED PRIMARY KEY auto_increment,
    student_name CHAR(30) COMMENT '学生名',
    gender CHAR(30) DEFAULT NULL    COMMENT '学生性别',
    class_id INT DEFAULT NULL COMMENT '班级id'
);

-- 老师表
CREATE TABLE teacher(
    id INT UNSIGNED PRIMARY KEY auto_increment,
    teacher_name CHAR(30) COMMENT '教师名'
);

-- 课程表
CREATE TABLE course(
 id INT UNSIGNED PRIMARY KEY auto_increment,
 course_name CHAR(30) COMMENT '课程名',
 teacher_id INT DEFAULT NULL COMMENT'教师id'
);

-- 成绩表
CREATE TABLE score(
    id INT UNSIGNED PRIMARY KEY auto_increment,
    number INT DEFAULT NULL COMMENT '分数',
    student_id INT DEFAULT NULL COMMENT '学生id',
    course_id INT DEFAULT NULL COMMENT '课程id'
);
#+header: :engine mysql
#+header: :dbhost localhost
#+header: :dbuser cloud
#+header: :dbpassword "password"
#+header: :database tuto
drop table score;
drop table student;
drop table course;
drop table classe;
drop table teacher;
#+header: :engine mysql
#+header: :dbhost localhost
#+header: :dbuser cloud
#+header: :dbpassword "password"
#+header: :database tuto
INSERT INTO student (student_name, gender, class_id) VALUES ('张三', 'M', 1);
INSERT INTO student (student_name, gender, class_id) VALUES ('李四', 'M', 2);
-- INSERT INTO student (student_name, gender, class_id) VALUES ('王五', 'F', 4);  
INSERT INTO classe (caption) VALUES ('一班');
INSERT INTO classe (caption) VALUES ('二班');
INSERT INTO classe (caption) VALUES ('三班');           

add foreign key

add foreign key muss be careful, the references must exist, such as -- INSERT INTO student (student~name~, gender, class~id~) VALUES ('王五', 'F', 4); will give error with add foreign key, because there are no such item in classe with id=4!!!!

#+header: :engine mysql
#+header: :dbhost localhost
#+header: :dbuser cloud
#+header: :dbpassword "password"
#+header: :database tuto
-- ALTER TABLE student DROP FOREIGN KEY student_class;
ALTER TABLE student ADD 
CONSTRAINT student_class 
FOREIGN KEY (class_id) 
REFERENCES classe(id)
ON DELETE CASCADE
ON UPDATE CASCADE;

#+header: :engine mysql
#+header: :dbhost localhost
#+header: :dbuser cloud
#+header: :dbpassword "password"
#+header: :database tuto
DELETE FROM classe WHERE id=2;
#+header: :engine mysql
#+header: :dbhost localhost
#+header: :dbuser cloud
#+header: :dbpassword "password"
#+header: :database tuto
UPDATE classe SET id=10 WHERE id=1;

left join

#+header: :engine mysql
#+header: :dbhost localhost
#+header: :dbuser cloud
#+header: :dbpassword "password"
#+header: :database tuto
select c.caption, s.student_name, s.gender from classe c left join student s on c.id=s.class_id;

right join

#+header: :engine mysql
#+header: :dbhost localhost
#+header: :dbuser cloud
#+header: :dbpassword "password"
#+header: :database tuto
select c.caption, s.student_name, s.gender from classe c right join student s on c.id=s.class_id;

inner join

#+header: :engine mysql
#+header: :dbhost localhost
#+header: :dbuser cloud
#+header: :dbpassword "password"
#+header: :database tuto
select c.caption, s.student_name, s.gender from classe c inner join student s on c.id=s.class_id;

full joipn

#+header: :engine mysql
#+header: :dbhost localhost
#+header: :dbuser cloud
#+header: :dbpassword "password"
#+header: :database tuto
select * from classe left join student on classe.id=student.class_id union  select * from classe right join student on classe.id=student.class_id;          

many2one

add more students to same class

#+header: :engine mysql
#+header: :dbhost localhost
#+header: :dbuser cloud
#+header: :dbpassword "password"
#+header: :database tuto
INSERT INTO student (student_name, gender, class_id) VALUES ('张五', 'M', 1);
INSERT INTO student (student_name, gender, class_id) VALUES ('李六', 'M', 2);
INSERT INTO student (student_name, gender, class_id) VALUES ('李七', 'M', 1);
INSERT INTO student (student_name, gender, class_id) VALUES ('李八', 'M', 1);
INSERT INTO student (student_name, gender, class_id) VALUES ('李九', 'M', 1);
#+header: :engine mysql
#+header: :dbhost localhost
#+header: :dbuser cloud
#+header: :dbpassword "password"
#+header: :database tuto
SELECT c.caption ,COUNT(s.student_name) student_num 
FROM classe c LEFT JOIN student s ON c.id=s.class_id 
GROUP BY c.id;
#+header: :engine mysql
#+header: :dbhost localhost
#+header: :dbuser cloud
#+header: :dbpassword "password"
#+header: :database tuto
select c.caption , s.student_name, s.gender from classe c left join student s on c.id=s.class_id;          

many2many

CREATE TABLE tag(
id INT UNSIGNED PRIMARY KEY auto_increment,
tag_name VARCHAR(50) NOT NULL
)

CREATE TABLE article(
id INT UNSIGNED PRIMARY KEY auto_increment,
title VARCHAR(100) NOT NULL
)

CREATE TABLE tag_article(
id INT UNSIGNED PRIMARY KEY auto_increment,
tag_id INT UNSIGNED DEFAULT NULL,
article_id INT UNSIGNED DEFAULT NULL,
FOREIGN KEY(tag_id) REFERENCES tag(id) ON DELETE CASCADE ON UPDATE CASCADE,
FOREIGN KEY(article_id) REFERENCES article(id) ON DELETE CASCADE ON UPDATE CASCADE,
UNIQUE(tag_id,article_id)
)


SELECT a.title 
FROM article a INNER JOIN tag_article t 
ON a.id=t.article_id 
WHERE tag_id=1







Operation from the third program language

singal python file connect with mysql

import pymysql
db = pymysql.connect("localhost", "root", "123456", "testforjava")
cursor = db.cursor()
sql = """create table  IF NOT EXISTS course(id int,  kurs_name varchar(50), kurs_length varchar(50),teacher varchar(50), categeory varchar(50))"""
cursor.execute(sql)
sql = """insert into course values(7, 'CLI', 22, 'su', 'basic')"""
cursor.execute(sql)
sql = """insert into course values(8, 'CLI', 22, 'su', 'basic')"""
cursor.execute(sql)
db.commit()

sql1 = """select * from course"""
cursor.execute(sql1)
results = cursor.fetchall()
print('\n')
for row in results:
    num = row[0]
    name = row[1]
    age = row[2]
    right = row[3]
    dis = row[4]
    print("num is %7s, name is %7s, age is %7s, right is %7s, dis is %7s" %
          (num, name, age, right, dis))

# if __name__ == "__main__":
cursor.close()

from pymysql import connect
from pymysql.cursors import DictCursor


class Pymysqlconnection:
    def __init__(self):
        self.conn = connect(
            host='localhost',
            port=3306,
            user='cloud',
            password='password',
            database='0812erp'
        )
        self.cursor = self.conn.cursor(DictCursor)

    def __def__(self):
        self.cursor.close()
        self.conn.close()

    def get_item(self):
        sql = 'select * from sys_user'
        self.cursor.execute(sql)
        for temp in self.cursor.fetchall():
            print(temp)


if __name__ == '__main__':
    pymysqlconnection = Pymysqlconnection()
    pymysqlconnection.get_item()

singal java file connect with mysql

import java.sql.*;
public class JavaConnSQL
{
    static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";  
    static final String DB_URL = "jdbc:mysql://localhost:3306/testforjava?useSSL=false&serverTimezone=UTC";
    static final String USER = "root";
    static final String PASS = "123456";
    public static void main( String[] args )
    {
        System.out.println( "Hello World!" );
        System.out.println("在dir中生成的代码, 如果dir中有驱动,则可以执行mysql的连接");
        System.out.println("提前执行");
        System.out.println("export CLASSPATH=mysql-connector-java-8.0.20.jar:. ");
        Connection conn = null;
        Statement stmt = null;
        try{
            Class.forName(JDBC_DRIVER);
            System.out.println("连接数据库...");
            conn = DriverManager.getConnection(DB_URL,USER,PASS);

            System.out.println(" 实例化Statement对象...");
            stmt = conn.createStatement();
            String sql;
            sql = "SELECT id, kurs_name FROM course";
            ResultSet rs = stmt.executeQuery(sql);

            while(rs.next()){
                int id  = rs.getInt("id");
                String name = rs.getString("kurs_name");
                // 输出数据
                System.out.print("ID: " + id);
                System.out.print(", kurs name 站点名称: " + name);
                System.out.print("\n");
            }
            rs.close();
            stmt.close();
            conn.close();
        }catch(SQLException se){
            // 处理 JDBC 错误
            se.printStackTrace();
        }catch(Exception e){
            // 处理 Class.forName 错误
            e.printStackTrace();
        }
    }
}

Footnotes

1

此后,电脑的root用户将不能登陆,而此时电脑的普通, 用户可以登陆,但是没有设置密码,不能用 -p 登陆


title: Postgresql

#+STARTUP: overview

basic OP

sudo apt install postgresql-client-common

sudo apt install postgresql postgresql-contrib

sudo -i -u postgres psql

swith to psql user (postgres, auto created), and then login in

sudo -u postgres psql

login psql from current user

\password{=latex} postgres; OR alter user postgres with PASSWORD 'new~password~';

set password

psql -h localhost -U 'user~name~' (with be asked for password)

login with password, for locally distributed or remotely
for remote login, please install at least one client version( install postgres-client-12)
Had to set listen_addresses='*' in postgresql.conf to allow for incoming connections from any ip / all ip
add <hostssl   all            all             0.0.0.0/0           md5> to allow ssl connection
if remotely, please check if the port is open

psql "sslmode=require host=141.5.103.1 port=5432 dbname=postgres" --username=postgres

ḑatabase \du{=latex} \q{=latex}

DROP SCHEMA public CASCADE;
CREATE SCHEMA public;
drop all table

src block

with header

#+header: :engine postgresql
#+header: :dbhost 141.5.103.1
#+header: :dbuser postgres
#+header: :dbpassword "xx"
#+header: :database postgres
create table personv (
 id int, 
 firstname varchar(50),
 lastname varchar(50),
 gender varchar(6),
 dataofbirth DATE
) ;
#+header: :engine postgresql
#+header: :dbhost 141.5.103.1
#+header: :dbuser postgres
#+header: :dbpassword "xxx"
#+header: :database postgres
CREATE TABLE articles (
  id SERIAL PRIMARY KEY,
  title VARCHAR(255),
  content TEXT,
  published_by INT,
  published_on TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  CONSTRAINT fk_articles_users FOREIGN KEY (published_by) REFERENCES users (id)
);

with session

\l
\d