vps中lnmp的快速备份、恢复与搬家

vps中lnmp的快速备份、恢复与搬家

现在VPS提供商越来越多,价格也越来越便宜,VPS搬家成为非常普遍的事。对于在VPS上通过lnmp建站的,很多都是使用传统方法,数据库导出,文件复制,nginx配置等等,其实,这一切只要用几句ssh命令,就可以快速完成。

首先是备份:

killall nginx
service mysql stop
tar zcvf /home/wwwroot/wwwroot.tar.gz /home/wwwroot
tar zcvf /home/wwwroot/nginx.tar.gz /usr/local/nginx/conf
tar zcvf /home/wwwroot/mysql.tar.gz /usr/local/mysql/var
/usr/local/nginx/sbin/nginx
service mysql start

运行以上语句后,会在wwwroot目录下生成3个备份文件,

wwwroot.tar.gz对应网站文件,nginx.tar.gz对应nginx配置文件,mysql.tar.gz对应数据库文件。

接下来是恢复,如果是本地恢复,直接运行下面语句:(这里假设3个备份文件都在/root目录下,如果在其他目录,请进行相应的路径修改)

killall nginx
service mysql stop
tar zxvf wwwroot.tar.gz
tar zxvf nginx.tar.gz
tar zxvf mysql.tar.gz
mv /usr/local/nginx/conf /usr/local/nginx/conf-bak
mv /usr/local/mysql/var /usr/local/mysql/var-bak
mv home/wwwroot /home/wwwroot
mv usr/local/nginx/conf /usr/local/nginx/conf
mv usr/local/mysql/var /usr/local/mysql/var
chown -R mysql /usr/local/mysql/var
chown -R www /usr/local/nginx/conf
/usr/local/nginx/sbin/nginx
service mysql start

如果是搬家,先用wget语句从另一台vps获取这3个备份文件,然后安装好lnmp,再执行以上语句就可以拉。

python 2.7 报错

Traceback (most recent call last):
File "/usr/lib/python3.2/urllib/request.py", line 1140, in do_open
h.request(req.get_method(), req.selector, req.data, headers)
File "/usr/lib/python3.2/http/client.py", line 970, in request
self._send_request(method, url, body, headers)
File "/usr/lib/python3.2/http/client.py", line 1008, in _send_request
self.endheaders(body)
File "/usr/lib/python3.2/http/client.py", line 966, in endheaders
self._send_output(message_body)
File "/usr/lib/python3.2/http/client.py", line 811, in _send_output
self.send(msg)
File "/usr/lib/python3.2/http/client.py", line 749, in send
self.connect()
File "/usr/lib/python3.2/http/client.py", line 727, in connect
self.timeout, self.source_address)
File "/usr/lib/python3.2/socket.py", line 397, in create_connection
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
socket.gaierror: [Errno -5] No address associated with hostname

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "python4beg.py", line 14, in <module>
response = request.urlopen('http://pythonforbeginners.com/')
File "/usr/lib/python3.2/urllib/request.py", line 139, in urlopen
return opener.open(url, data, timeout)
File "/usr/lib/python3.2/urllib/request.py", line 370, in open
response = self._open(req, data)
File "/usr/lib/python3.2/urllib/request.py", line 388, in _open
'_open', req)
File "/usr/lib/python3.2/urllib/request.py", line 348, in _call_chain
result = func(*args)
File "/usr/lib/python3.2/urllib/request.py", line 1160, in http_open
return self.do_open(http.client.HTTPConnection, req)
File "/usr/lib/python3.2/urllib/request.py", line 1143, in do_open
raise URLError(err)
urllib.error.URLError: <urlopen error [Errno -5] No address associated with hostname>

 

/usr/local/python2.7/lib/python2.7/socket.py

Original Code:

def create_connection(.....)

host, port = address
err = None
for res in getaddrinfo(host, port, 0, SOCK_STREAM):

Edited Code:

def create_connection(.....)

host, port = address
err = None
hostip = gethostbyname(host)
for res in getaddrinfo(hostip, port, 0, SOCK_STREAM):

IPHONE6 IOS8 安装GCC

大量宝贝在此:

http://apt.saurik.com/debs/

libgcc: http://apt.saurik.com/debs/libgcc_4.2-20080410-1-6_iphoneos-arm.deb
gcc: http://apt.saurik.com/debs/iphone-gcc_4.2-20080604-1-8p_iphoneos-arm.deb
gdb: http://apt.saurik.com/debs/gdb_1518-12p_iphoneos-arm.deb
make: http://apt.saurik.com/debs/make_3.81-2p_iphoneos-arm.deb
用dpkg -i *.deb安装

 

然后编译  gcc -o hi hi.c

直接执行./hi会报Illegal instruction: 4错误

此扫执行 sed -i” ‘s/\x00\x30\x93\xe4/\x00\x30\x93\xe5/g;s/\x00\x30\xd3\xe4/\x00\x30\xd3\xe5/g;’ hi

然后 执行./hi 就可以了

Aajaxterm在Firefox Chrome下布局混乱的解决方案

同样在的问题还存在于上翻不能使用

使用以下的ajaxterm.css替代原来的即可 重启后生效解决上述问题

<pre>pre.stat {
	margin: 0px;
	padding: 4px;
	display: block;
	font-family: monospace;
	white-space: pre;
	background-color: black;
	border-top: 1px solid black;
	color: white;
}
pre.stat span {
	padding: 0px;
}
pre.stat .on {
	background-color: #080;
	font-weight: bold;
	color: white;
	cursor: pointer;
}
pre.stat .off {
	background-color: #888;
	font-weight: bold;
	color: white;
	cursor: pointer;
}
#term {
	float: left;
	margin: 0px;
	padding: 4px;
	display: block;
	font-family: monospace;
	white-space: pre;
	background-color: black;
	border-top: 1px solid white;
	color: #eee;
}
span.f0  { color: #000; }
span.f1  { color: #b00; }
span.f2  { color: #0b0; }
span.f3  { color: #bb0; }
span.f4  { color: #00b; }
span.f5  { color: #b0b; }
span.f6  { color: #0bb; }
span.f7  { color: #bbb; }
span.f8  { color: #666; }
span.f9  { color: #f00; }
span.f10 { color: #0f0; }
span.f11 { color: #ff0; }
span.f12 { color: #00f; }
span.f13 { color: #f0f; }
span.f14 { color: #0ff; }
span.f15 { color: #fff; }
span.b0  { background-color: #000; }
span.b1  { background-color: #b00; }
span.b2  { background-color: #0b0; }
span.b3  { background-color: #bb0; }
span.b4  { background-color: #00b; }
span.b5  { background-color: #b0b; }
span.b6  { background-color: #0bb; }
span.b7  { background-color: #bbb; }

body { background-color: #888; }
</pre>

python验证码认别

python的Python Imaging Library (PIL) 图形处理库提供了强大的图像处理功能,本验证码认别基于DISCUZ png格式图片的认别 基本过程如下:

1,将图片去燥 通过观察可知一般验证码图片的背景色一般较为浅色,通过实验得出RGB三通道同时值大于170,虽然有可能遗漏少数的浅色字符,但是是大大的提升了认别的正确率,这是值得的。

2,二值化  3,训练样本  4 认别


#!/usr/bin/env python
#coding:utf-8

import Image,ImageFont,ImageDraw
import os,sys
from math import atan2,pi
import pickle

import psyco
psyco.full()

DURATION = 1000
DIAMETER = 20
COLORDIFF = 10
TEXTCOLOR = (128,128,128)
BACKGROUND = (255,255,255)
MODE = 'sample'
samples = None

def printframe(im,code=-1):
frame = im.load()
(w,h) = im.size
for j in xrange(0,h,2):
for i in xrange(0,w,2):
if (code == -1 and frame[i,j] !=BACKGROUND) or (code != -1 and frame[i,j]==code) :
print '*',
else:
print ' ',
print

def printregion(region):
frame = region.getdata()
(w,h)=region.size
for i in range(h):
for j in range(w):
if frame[i*w+j] != BACKGROUND:
print '*',
else:
print ' ',
print

def purify(region):
frame = region.getdata()
(w,h)=region.size
for i in range(h):
for j in range(w):
if frame[i*w+j] != BACKGROUND and frame[i*w+j] != (0,0,0):
region.putpixel( (j,i), TEXTCOLOR )
else:
region.putpixel( (j,i), BACKGROUND )
return region

def isnoise(points):
'''Determine if the points are noisy points'''

if len(points)<=20:
return True

# center point
left = 255
right = 0
upper = 255
lower = 0
center = [0,0]
for point in points:
center[0]+=point[0]
center[1]+=point[1]
center[0]/=len(points)
center[1]/=len(points)

distance = 0
farpoints = 0
for point in points:
dd = (point[0]-center[0])*(point[0]-center[0])+(point[1]-center[1])*(point[1]-center[1])
distance += dd
if dd > DIAMETER*DIAMETER:
farpoints += 1
if point[0]<left:
left = point[0]
if point[0]>right:
right = point[0]
if point[1]<upper:
upper = point[1]
if point[1]>lower:
lower = point[1]
area = abs(left-right)*abs(upper-lower)

if farpoints>=1 or ( farpoints>=0 and (area==0 or 1.0*len(points)/area<0.35) ):
return True
else:
print farpoints
print 1.0*len(points)/area
return False

def samecolor(rgb1,rgb2):
diff = 0
for i in range(3):
diff += abs(rgb1[i]-rgb2[i])
if diff < COLORDIFF:
return True
else:
return False

def totif(fname):
im = getframe(fname)
im.save(fname[:4]+'.tif','TIFF')

def getframe(fname):
'''return w*h key frame without noise'''
#open image
im = Image.open(fname)
frame = None
bkframe = []
im = im.convert('RGB')
frame = im.load()

# count same color
(w,h) = im.size
d = {}
for i in xrange(w):
for j in xrange(h):
#    print im.getpixel((i,j))
k = frame[i,j]
#            print k[0],k[1],k[2]
if k[0] > 190 and k[1]>190 and k[2] > 190:
frame[i,j]=BACKGROUND
k = BACKGROUND
if d.has_key(k):
d[k][0] += 1
d[k].append((i,j))
else:
d[k] = [1,(i,j)]
topd = sorted(d.items(),cmp=lambda x,y:cmp(y[1][0],x[1][0]))

# denoize2: group similar color
cgrp = {}
for k in d.keys():
cgrp[k] = k
for k1 in cgrp.keys():
for k2 in cgrp.keys():
if k1 != k2 and cgrp[k1] == k1 and samecolor(k1,k2):
cgrp[k2]=k1
d = {}
for i in xrange(w):
for j in xrange(h):
k = frame[i,j]
k = cgrp[k]
if d.has_key(k):
d[k][0] += 1
d[k].append((i,j))
else:
d[k] = [1,(i,j)]
#    topd = sorted(d.items(),cmp=lambda x,y:cmp(y[1][0],x[1][0]))

for i in xrange(w):
for j in xrange(h):
frame[i,j]=BACKGROUND

found = 0
for (k,v) in topd[1:]:
if not isnoise(v[1:]):
#        if True:
for point in v[1:]:
frame[point[0],point[1]]=k
found += 1
print found,
#            printframe(im,k)
#            raw_input()
if found == 4:
break
print

# denoize again
for i in xrange(w):
for j in xrange(h):
if frame[i,j] != BACKGROUND:
count = 0
for m in xrange( max(0,i-1), min(i+2,w) ):
for n in xrange( max(0,j-1), min(j+2,h) ):
if frame[m,n] != BACKGROUND:
count += 1
if count <= 1:
frame[i,j] = BACKGROUND
im = fillholes(im)
return im

def loadsamples():
pks = pickle.load(open('samples.pk','rb'))
samples = {}
for (pk,v) in pks.items():
im = Image.new('RGB',pk[0])
r = im.crop((0,0,pk[0][0],pk[0][1]))
r.fromstring(pk[1])
samples[r] = v
return samples

def loadttf():
files = [ 'ttf/'+x for x in os.listdir('ttf') ]
fonts = []
for f in files:
fonts.append( ImageFont.truetype(f,32) )

regions = []
regionsv = []
for font in fonts:
im = Image.new( 'RGB', (1000,50), BACKGROUND )
draw = ImageDraw.Draw(im)
draw.text(  (0,0),"B C E F G H J K M P Q R T V W X Y 2 3 4 6 7 8 9"\
,font=font,fill=TEXTCOLOR )
regions.extend( imdiv(im) )
regionsv.extend( 'B C E F G H J K M P Q R T V W X Y 2 3 4 6 7 8 9'.split(' ') )

for i in xrange(len(regions)):
regions[i] = docrop(regions[i])
printregion( regions[i] )

kv = {}
for i in range(len(regions)):
kv[regions[i]] = regionsv[i]

return kv

def distance(r1,r2):
den1 = density(r1)
den2 = density(r2)
if 1.0*den1/den2>1:
(den1,den2) = (den2,den1)
r1 = r1.resize(r2.size)
d1 = r1.getdata()
d2 = r2.getdata()
same = [0,0]
total = [0,0]
for i in xrange(len(d1)):
if d1[i] != BACKGROUND:
total[0] += 1
if d1[i] == d2[i]:
same[0] += 1
if d2[i] != BACKGROUND:
total[1] += 1
if d1[i] == d2[i]:
same[1] += 1
return 1 - 1.0*same[0]/total[0] * 1.0*same[1]/total[1] * 1.0*den1/den2

def match(region,samples):
if samples == {}:
return None
dists = []
for (k,v) in samples.items():
dists.append( (distance(region,k),v) )
dists.sort()
if MODE == 'sample':
return dists[0][1]
else:
i = 0
while dists[i][1] in ['H','I']:
i += 1
return dists[i][1]
#    printregion( region )
#    printregion( samples[ dists[0][1] ] )

def fillholes(region):
SCORE = 9
if density(region) > 0.5:
SCORE = 14
(w,h) = region.size
turn = 0
while turn < 1:
turn += 1
for i in range(1,w-1):
for j in range(1,h-1):
if region.getpixel((i,j)) == BACKGROUND:
score = 0
for m in range(i-1,i+2):
for n in range(j-1,j+2):
if region.getpixel((m,n)) != BACKGROUND:
if m == i or n == j:
score += 3
else:
score += 1
if score >= SCORE:
region.putpixel((i,j),TEXTCOLOR)
return region

def imdiv2(im):
divs = {}
frame = im.load()
(w,h) = im.size
for i in range(w):
for j in range(h):
color = frame[i,j]
if color != BACKGROUND:
if divs.has_key( color ):
divs[ color ].append( (i,j) )
else:
divs[ color ] = [ (i,j) ]

regions = []
divs = [ (x[0],sorted(x[1],cmp=lambda x,y:cmp(x[1],y[1]))) for x in  divs.items() ]
divs.sort(cmp=lambda x,y:cmp(x[1][0],y[1][0]))
for (color,pts) in divs:
xs = [ x[0] for x in pts ]
ys = [ x[1] for x in pts ]
box = ( min(xs), min(ys), min(max(xs)+1,w), min(max(ys)+1,h) )
regions.append(im.crop(box))

return regions

def imdiv(im):
'''div and return pieces of pics'''
frame = im.load()
(w,h) = im.size
horis =  []
for i in range(w):
for j in range(h):
if frame[i,j] != BACKGROUND:
horis.append(i)
break
horis2 = [max(horis[0]-2,0)]
for i in range(1,len(horis)-1):
if horis[i]!=horis[i+1]-1:
horis2.append((horis[i]+horis[i+1])/2)
horis2.append(min(horis[-1]+3,w))
boxes=[]
for i in range(len(horis2)-1):
boxes.append( [horis2[i],0,horis2[i+1],h]  )
for k in range(len(boxes)):
verts = []
for j in range(h):
for i in range(boxes[k][0],boxes[k][2]):
if frame[i,j] != BACKGROUND:
verts.append(j)
boxes[k][1] = max(verts[0]-2,0)
boxes[k][3] = min(verts[-1]+3,h)
if boxes == []:
return None
regions = []
for box in boxes:
regions.append( im.crop(box) )
return regions

def getcrop(region):
frame = region.getdata()
(w,h)=region.size
pts = []
ptsi = []
for i in range(h):
for j in range(w):
if frame[i*w+j] != BACKGROUND and frame[i*w+j] != (0,0,0):
pts.append((i,j))
ptsi.append((j,i))
if pts == []:
return [0,0,1,1]
pp1 = min(pts)
pp2 = max(pts)
pp3 = min(ptsi)
pp4 = max(ptsi)
return [pp3[0],pp1[0],pp4[0]+1,pp2[0]+1]

def density(region):
frame = region.getdata()
(w,h) = region.size
area_all = w*h
area = 0
for i in range(h):
for j in range(w):
if frame[i*w+j] != BACKGROUND and frame[i*w+j] != (0,0,0):
area += 1
return 1.0*area/area_all

def docrop(region):
croppos = getcrop(region)
newregion = region.crop(croppos)
return newregion

def dorotate(region):
#    printregion(region)
deg = 0
maxdens = 0
for i in range(-30,31):
dens = density( docrop( region.rotate(i) ) )
if dens > maxdens:
deg = i
maxdens = dens
#    printregion( doresize( region.rotate(deg) ) )
return region.rotate(deg)

def normalize(im):
# divide im
regions = imdiv(im)
if len(regions)!=4:
regoins = imdiv2(im)

for k in range(len(regions)):
regions[k] = dorotate(regions[k])
regions[k] = purify( docrop(regions[k]) )

return regions

def train(im):
global samples
try:
samples = pickle.load(open('samples.pk','rb'))
except:
samples = {}
pickle.dump(samples,open('samples.pk','wb'))

regions = normalize(im)
for region in regions:
#        (w,h)=region.size
#        region = region.resize((w*.8,h*.8))
printregion(region)
smps = loadsamples()
print match(region,smps).upper()
print 'enter [0-9a-z] to add to library: '
ans = raw_input()
if len(ans) == 1:
key = (region.size,region.tostring())
samples[key] = ans[0]
pickle.dump(samples,open('samples.pk','wb'))

def crackcode(im):
global samples
if not samples:
samples = loadsamples()
regions = normalize(im)
s = []
ans = []
for r in regions:
s.append(match(r,samples).upper())
messup = ['FE','38','72','HK','8B','YV','VY']
for i in range(len(s)):
for mess in messup:
if s[i] == mess[0]:
s[i] = mess
if len(s) != 4:
return ['failed']
else:
for s1 in s[0]:
for s2 in s[1]:
for s3 in s[2]:
for s4 in s[3]:
t = s1+s2+s3+s4
ans.append(t)
return ans

if __name__ == '__main__':
if len(sys.argv) == 2:
if sys.argv[1].startswith('train'):
trainfiles = os.listdir(sys.argv[1])
trainfiles.sort()
for trainfile in trainfiles:
trainfile = sys.argv[1]+'/'+trainfile
print trainfile
im = getframe(trainfile)
train(im)
else:
if MODE == 'sample':
samples = loadsamples()
else:
samples = loadttf()
#        results = {}
for i in range(72,200):
im = getframe('%d.jpeg'%i)
print i,"hahaha"
printframe(im)
ans = crackcode(im)
print ans
filestream = open("result.txt",'w')
filestream.write(str(ans))
filestream.close()
#print results

python_verification

C++ primer 学习1

1.数据成员mutable关键字

有时我们希望类的数据成员可以被改变甚至被const成员函数改变,则将成员变量声明为mutable来实现,尽管某个成员函数是const,但是仍然可以改变这个变量。

2.构造函数的初始化列表


Class hust{

Public:

Hust():name(“”),score(0){}

Private:

Std::string name;

Int scroe;

};

构造函数不可以声明为const函数,因为运行一个普通的构造函数就是用来初始化成员变量的,并且不管一个成员是否为const类型,都可以用构造函数进行初始化。初始化列表只能在类内定义而不是只是声明指定。例如 hust(const string No):Xuehao(No),name(“”),score(0){}

使用构造函数初始化列表的必要性:在对具有const属性的成员变量初始化时只有在构造函数初始化列表中才有机会进行初始化,这是唯一的机会。另外初始化可以是任意的表达式,例如:score(20*5).

3.explicit关键字一致由构造函数隐式的转换


Class hust

{public:

Explicit hust(const std::string nm = “”):name(nm),…..{}

};

同时explicit关键字只能在类内使用,在类外定义是错误的。


Hust huster;

Huster.same_student(“wgl”); //error

Huster.same_student(hust(“wgl”)); //correct

Explicit关键字抵制了构造函数的隐式转换,避免了阿狸地一个测试完成后的丢弃的对象,然后再一次对这个对象引用的错误。

4.友元

有时候允许特定的非成员函数访问一个类的私有成员方法,同时仍然阻止一般的访问。Friend只能出现在类的内部。


Class hust{

Friend class swu;

********************

};

Int swu::getname(hust & huster,int age)

{

//访问了hust类的私有成员,此时所有hust的私有成员在swu的成员函数中都可以被访问

Return huster.age+age-18;

}

限制某个函数使用


Class hust{

Friend int swu::getname(hust&huster,int age);

};

此时只有swu类的getname成员函数可以访问hust的private成员变量。

wordpress 调用函数更新文章

直接插入数据库 字段太多混乱 同时MYSQL 还得支持外连 很多虚拟空间不支持

我们可以利用 wordpress 自带的函数 wp_insert_post 调用插入一个新的文章  如果你采集的文章直接使用一个post操作就可以了

方便实用 简单 何乐而不用呢


<?php

define( 'ABSPATH', dirname(__FILE__) . '/' );
require_once( ABSPATH . 'wp-config.php' );
require_once( ABSPATH . 'wp-settings.php' );
require_once( ABSPATH . 'wp-includes/class-wp.php' );
require_once( ABSPATH . 'wp-includes/functions.php' );
require_once( ABSPATH . 'wp-includes/plugin.php' );
$title = $_POST["title"];
$content = $_POST["content"];
$tags = explode("_",$_POST["tags"]);
$cate = $_POST["cate"];
//print_r $tags;
//
//
$wp = new WP();
$wp->main();
//
$my_post = array();
$my_post['post_title'] = $title;
$my_post['post_content'] = $content;
$my_post['post_status'] = 'publish';
$my_post['post_author'] = 1;
$my_post['post_category'] = array($cate);
$my_post['tags_input'] = $tags;
//$my_post['tags_input'] = array('tag1', 'tag2');
//$my_post['post_status'] = 'future';
////$my_post['post_date'] = '2010-07-04 16:20:03';

// Insert the post into the database
$ret = wp_insert_post( $my_post );
echo $ret;
?>

下面是更带更新图片版因为有些网站屏蔽了盗链接 小气

<?php
define( 'ABSPATH', dirname(__FILE__) . '/' );
require_once( ABSPATH . 'wp-config.php' );
require_once( ABSPATH . 'wp-settings.php' );
require_once( ABSPATH . 'wp-includes/class-wp.php' );
require_once( ABSPATH . 'wp-includes/functions.php' );
require_once( ABSPATH . 'wp-includes/plugin.php' );
$pic_name = $_POST["pic_name"];
$pic = $_POST["pic"];
if($pic != "" && $pic_name != "")
{
$path = "images/";
$pic_name = $path.$pic_name;
echo $pic_name;
echo "||";
error_reporting(0);
mkdir("images");
$handle = fopen($pic_name, 'w');
echo fwrite($handle,file_get_contents($pic));
}

$title = $_POST["title"];
$content = $_POST["content"];
$tags = explode("_",$_POST["tags"]);
$cate = $_POST["cate"];
//print_r $tags;
//
//
$wp = new WP();
$wp->main();
//
$my_post = array();
$my_post['post_title'] = $title;
$my_post['post_content'] = $content;
$my_post['post_status'] = 'publish';
$my_post['post_author'] = 1;
$my_post['post_category'] = array($cate);
$my_post['tags_input'] = $tags;
//$my_post['tags_input'] = array('tag1', 'tag2');
//$my_post['post_status'] = 'future';
////$my_post['post_date'] = '2010-07-04 16:20:03';

// Insert the post into the database
$ret = wp_insert_post( $my_post );
echo $ret;
?>

插入效果看图 不看广告看效果