突然无聊 学学emacs [该记录用vim编写]

交换

setxkbmap -option "ctrl:swapcaps"

1
2
显示行号
M-x linum-mode
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
                 M-v
C-p
|
M-a C-a M-b C-b Cursor C-f M-f C-e M-e
|
C-n
C-v
取消 操作 C-g
退出 C-x C-c
剪切 删除 C-d
C-k
粘贴 C-y
撤销 C-x u
C-/
C-_

文件

1
2
3
4
5
6
7
8
9
10
11
12
打开 C-x C-f
保存 C-x C-s
C-x C-w : save file as

保存多个缓存区 C-x s

显示缓冲区 C-x C-b

切换缓存区 C-x b

关闭其它所有窗格 只保留一个
C-x 1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
文字替换      M-x repl s<Return>src<Return>dst<Resturn>
恢复自动保存的 M-x recover

切换模式
M-x fundamental-mode (主模式)
M-x text-mode (文本模式)
M-x auto-fill-mode (自动 折 行 模式) C-u 20 C-x f 设置折叠字符数为20
M-q 手动折叠行

查看主模式的文档 C-h m

搜索 C-s
在搜索中再按C-s可以往后搜索 C-r 与之搜索方向相反

C-x 2 上下分割窗口
C-x 3 左右

C-M-v下别的移动 C-M-S-v上移动
切换到其它窗口 C-x o

打开文件 并跳过去
C-x 4 C-f 上下
`

显示行号
M-x linum-mode

1

             M-v
             C-p
              |

M-a C-a M-b C-b Cursor C-f M-f C-e M-e
|
C-n
C-v
取消 操作 C-g
退出 C-x C-c
剪切 删除 C-d
C-k
粘贴 C-y
撤销 C-x u
C-/
C-_

1
2
3
4

# 文件


打开 C-x C-f
保存 C-x C-s
C-x C-w : save file as

保存多个缓存区 C-x s

显示缓冲区 C-x C-b

切换缓存区 C-x b

关闭其它所有窗格 只保留一个
C-x 1

1
2
3

---

文字替换 M-x repl ssrcdst
恢复自动保存的 M-x recover

切换模式
M-x fundamental-mode (主模式)
M-x text-mode (文本模式)
M-x auto-fill-mode (自动 折 行 模式) C-u 20 C-x f 设置折叠字符数为20
M-q 手动折叠行

查看主模式的文档 C-h m

搜索 C-s
在搜索中再按C-s可以往后搜索 C-r 与之搜索方向相反

C-x 2 上下分割窗口
C-x 3 左右

C-M-v下别的移动 C-M-S-v上移动
切换到其它窗口 C-x o

打开文件 并跳过去
C-x 4 C-f 上下


=.= 已经基本放弃了 继续vim

该书版本2015.06

基于个人已有知识整理 低分享价值

章节

  1. java 是什么 java web是什么
  2. 各种java web容器 以及IDE的使用
  3. Servlet without jsp
  4. basic jsp syntax ,jsp 和servlet 在server端的互相forward
  5. cookie/session 以及相关安全知识
  6. jsp 表达式语句 $,#
  7. jsp 标签库 c fmt fn x sql
  8. jsp 自定义标签与函数库 .tag .tld
  9. 过滤器 (日志 验证 压缩加密 错误处理)
  10. WebSocket 进行交互 (ajax,adobe flash等 各类访问 的设计) 在线对战井字棋 集群
  11. 日志监控
  12. Spring

Source code

Here

相关

runnoob jsp

tomcat 个人理解

和php+apache类似

遇到请求是jsp则找jsp

如果是其它url则根据/WEB-INF/web.xml的servlet配置去找对应的class (这些都没有main函数 继承自HttpServlet)

配置web.xml也可以用java 的@WebServlet注解代替

依赖

sudo apt-get install default-jdk idea tomcat8

把个人用户添加到tomcat8的组里[???必要么]

servlet

文件上传 @MultipartConfig()

1
2
3
4
5
@MultipartConfig(
fileSizeThreshold = 5_242_880,//小于5MB保存在内存中
maxFileSize = 20_231L , //5~20MB保存在location(可设置 不设置则java默认)
maxRequestSize = 41_943_040L //拒绝>20MB文件 或 >40MB请求
)

通过request.getParameter(“action”)来判断 是要 请求 上传 下载 还是什么操作(下载需要注意设置返回头)

request.getPart(“file1”)来接受上传的文件

jsp

<%@ 指令 %> 例如说明文档 类型 引入依赖等
<% page %>
<% include %>
<% taglib %>
<%! 声明 %> 如声明定义变量 函数
<% 脚本 %> 赋值运算 貌似也可以在这里声明
<%= 表达式 %>运算
<%– 注释 –%>运算

表达式语句保留字 true false null instanceof empty div mod and or not eq ne lt gt le ge

表达式 的流处理 以及lambda

java 标准标签库规范的5个标签库 c 核心,fmt 格式化, fn 函数, sql, x XML

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
<%@ taglib prefix="c" uri="https://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="https://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="fn" uri="https://java.sun.com/jsp/jstl/fn" %>
<%@ taglib prefix="sql" uri="https://java.sun.com/jsp/jstl/sql" %>
<%@ taglib prefix="x" uri="https://java.sun.com/jsp/jstl/x" %>


<c:out value="${exp}" default="value is null">
<c:out value="${exp}">value is null</c:out>

<c:url value="http://....../today.jsp">
<c:param name="story" value="${storyId}">
<c:param name="seo" value="${seoString}">
</c:url>

<c:if test=>
balabala
</c:if>
c:choose c:when c:otherwise c:forEach c:forTokens c:redirect c:import c:set c:remove

fmt:message fmt:setLocale fmt:bundle fmt:setBundle fmt:requestEncoding fmt:timeZone fmt:setTimeZone fmt:formatDate fmt:parseDate fmt:formatNumber fmt:parseNumber
对应还有i18n的配置

(不推荐)sql:transaction sql:update sql:param sql:dateParam sql:query

(x 命名空间)

过滤器

继承Filter 重写函数doFilter init destroy,通过chain.doFilter向下传递

也可以在java内用代码配置 FilterGegistration

因为排序问题请勿使用注解来配置过滤器 (URL映射优先级 > Servlet映射)

filter-mapping可以用 不同方式配置 需要过滤的链接

1
2
3
4
5
6
7
8
9
<filter>
<filter-name>myf</filter-name>
<filter-class>com.wrox.fff</filter-class>
</filter>
<filter-mapping>
<filter-name>myf</filter-name>
<url-pattern>/foo</url-pattern>
<servlet-name>ticketServlet</servlet-name>
</filter-mapping>

压缩过滤器extends HttpServletResponnseWrapper

WebSocket

会使用443(wss)端口 以及Http/1.1中的 Connection:Upgrade

HTTP开始 然后用TCP连接的WebSocket交流

1
2
3
4
5
6
7
8
9
10
11
12
var connection = new WebSocket('ws://www.example.net/safsd');
var connection = new WebSocket('wss://secure.example.net/safsd');
var connection = new WebSocket('ws://www.example.net/safsd','asdf');
var connection = new WebSocket('ws://www.example.net/safsd',{'wer','qwef'});

if(connection.readyState == WebServlet.OPEN){qwer;}


connection.onopen = function(event){}
connection.onclose = function(event){}
connection.onerror = function(event){}
connection.onmessag = function(event){}

利用WebSocket可以实现 在线对战游戏 比如 井字棋

Server:

session来记录用户

@ServerEndpoint("/ticTacToe/{gameId}/{username}")

onOpen()

onMessage()

onClose()

发送消息

session.getBasicRemote().sendText(ttttteeeeexxxxxttttt)以及 close的另外的函数

前端js

上面的new WebSocket(*)on* + server.send


用WebSocket 做集群

@ClientEndpoint

ClusterMessage

做用户端的 extends HttpServlet

日志监控

maven -> org.apache.logging.log4j -> log4j-api/log4j-core/...

System.err.println/Sytem.out.println并不完美 因为它们永远启用 并在代码中

要记录的内容:错误/警告/错误类型/栈/JVM状态/一些需要审核的事的记录 比如医院

记录方法:普通的println/平面日志/XML/JSON/ linux的syslog/套接字/SMTP SMS/DB

分级:重要性 n MB/s的日志 = 无日志 ,例如java.util.logging.Level分类 (也有其它分类 如apache的不同级别)

  • 致命/崩溃 无常量
  • 错误 SEVERE
  • 警告 WARNING
  • 信息 INFO
  • 配置细节 CONFIG
  • 调试 FINE
  • 追踪1/2 FINER FINEST

通过 java.util.logging.LogManager解耦合,注意日志必要性和性能影响的权衡

框架 log4j,slf4j,logback,log4j2

log4j2的 记录器(),日志储存器,布局,过滤器

log4j2将寻找 log4j2log4j2-test支持的扩展类型有.xml,.json.jsn

Spring framework

其它

java编译后 单个实现不能超过65535个字节=.=……….

哇 心态崩了–google一堆资料能运行的没几个,以及上来就是一大堆代码,一点循序渐进的学习过程都没有,而且也没有不用和用的对比显示的区别

最后还是看了实验楼爸爸的spring教程,感谢!!感谢!!


我使用的环境

  • OS:4.9.0-deepin4-amd64 是Debian分 支下类似Ubuntu的
  • javac/java: javac 1.8.0_111 [apt-get install default-jdk]
  • maven : Apache Maven 3.3.9
  • idea : 2017.1

然后 学spring之需要有些的基础知识,个人认为是必备

代码层面的基础

  • JAVA SE/ core-java /就是基本的语法 类啊 继承啊 IO啊之类的东西
  • xml 这个看得很快的 就是个xml是个怎样的数据结构

要用的工具层面

  • maven [apt-get install maven] 看看5Min GuideGetting start 不需要太细 但要理解单独的maven是个啥
  • javac 大自感受了一下java的代码中的.和文件路径的/的关系
  • idea [apt-get install idea] 我用的IDE

知识层面


然后学习路径跟着实验楼爸爸的教程就好了 :-) 这里只做一些个人的笔记

idea相关

总的流程讲道理比eclipse简洁太多

Ctrl+Alt+Shift+SModules->Sources 代码根目录需要Mark as为Sources才能 右键添加Java类:-),resources文件夹也需要Mark as 成Resources

新建类 直接输入从起始到类名 如 com.abc.HelloWorld

运行左边的Edit Configurations->左上角加号->Application->设置Main class即可

新建xml中有spring选项简直完美

maven 相关

pom.xml中需要加上对spring的具体的某些库的依赖的配置 然后idea/maven会自动帮你下载:-)

spring 相关

一个bean 的 id 是一个随意的名字 它可以被java代码通过改名字得到

class是对应的Java代码的具体的类

name/value以键值对的形式 设置class类中的name对应的field

1
2
3
4
<bean id="FileNameGenerator" class="com.shiyanlou.spring.bean.FileNameGenerator">
<property name="name" value="shiyanlou"/>
<property name="type" value="txt"/>
</bean>

把bean设为另一个bean的使用ref

1
2
3
4
5
6
7
8
9
<bean id="CustomerBean" class="com.shiyanlou.spring.innerBean.Customer">
<property name="person" ref="PersonBean" />
</bean>

<bean id="PersonBean" class="com.shiyanlou.spring.innerBean.Person">
<property name="name" value="shiyanlou" />
<property name="address" value="chengdu" />
<property name="age" value="25" />
</bean>

用java代码得到bean

1
2
context = new ClassPathXmlApplicationContext("SpringBeans.xml");   //xml的文件名
Customer obj = (Customer) context.getBean("CustomerBean"); //上面的一个具体的id

bean的参数scope

  1. singleton — 单例模式,由 IOC 容器返回一个唯一的 bean 实例。
  2. prototype — 原型模式,被请求时,每次返回一个新的 bean 实例。
  3. request — 每个 HTTP Request 请求返回一个唯一的 Bean 实例。
  4. session — 每个 HTTP Session 返回一个唯一的 Bean 实例。
  5. globalSession — Http Session 全局 Bean 实例。

example:

<bean id="CustomerService" class="com.shiyanlou.spring.customer.services.CustomerService" scope="prototype"/>


bean 除了基本的int string也支持java的list map等 见实验楼爸爸的文档


代码中的spring @Component

1
2
3
4
5
6
packeage com.shiyanlou.spring;

@Component("shiyanlou")
public class shiyanlou{

}

与在XML中配置以下效果相同

1
<bean id="shiyanlou" class="com.shiyanlou.spring.shiyanlou">

还有@Autowired,@Configuration@Bean


自动扫描组件 减少 xml的繁琐配置

@Component +@Autowired+

1
<context:component-scan base-package="com.shiyanlou.spring" />

默认情况下,Spring 将把组件 Class 的第一个字母变成小写,来作为自动扫描组件的名称,例如将 CustomerService 转变为 customerService


增加代码阅读性

  1. @Component ——表示一个自动扫描 component
  2. @Repository ——表示持久化层的 DAO component
  3. @Service ——表示业务逻辑层的 Service component
  4. @Controller ——表示表示层的 Controller component

用filter+regex来include 省去@Component

1
2
3
4
<context:component-scan base-package="com.shiyanlou.spring" >
<context:include-filter type="regex" expression="com.shiyanlou.spring.dao.*DAO.*" />
<context:include-filter type="regex" expression="com.shiyanlou.spring.services.*Service.*" />
</context:component-scan>

自动装配Bean 属性autowire //自动装配如果找不到即为null

  1. no —— 默认情况下,不自动装配,通过 ref attribute手动设定。
  2. byName —— 根据 Property 的 Name 自动装配,如果一个 bean 的 name ,和另一个 bean 中的 Property 的 name 相同,则自动装配这个 bean 到 Property 中。
  3. byType —— 根据 Property 的数据类型( Type )自动装配,如果一个 bean 的数据类型,兼容另一个 bean 中 Property 的数据类型,则自动装配。
  4. constructor —— 根据构造函数参数的数据类型,进行 byType 模式的自动装配。
  5. autodetect —— 如果发现默认的构造函数,用 constructor 模式,否则,用 byType 模式。

spring 之 AOP

Advice

需要CGLIB2库 据搜索说是因为spring的aop的实现是基于该库

四种Advice 调用前 调用后 抛出异常 围绕,通过java实现spring的对应interface的类A,再通过xml配置target要切入的类B 和用来切入A 即可对指定类进行切入.deamo:

1
2
3
4
5
6
7
8
<bean id="customerServiceProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="target" ref="customerService" />
<property name="interceptorNames">
<list>
<value>hijackAroundMethodBean</value>
</list>
</property>
</bean>

Pointcut & Advisor

在上面的基础上再用 这两个 可以对指定的function才做切入

  • Advice:向程序内部注入的代码。
  • Pointcut:注入 Advice 的位置,切入点,一般为某方法。
  • Advisor: Advice 和 Pointcut 的结合单元,以便将 Advice 和 Pointcut 分开实现灵活配置。

auto proxy

代替ProxyFactoryBean用BeanNameAutoProxyCreator来自动批量切面,demo:

1
2
3
4
5
6
7
8
9
10
11
12
13
<bean
class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
<property name="beanNames">
<list>
<value>*Service</value>
</list>
</property>
<property name="interceptorNames">
<list>
<value>customerAdvisor</value>
</list>
</property>
</bean>

AspectJ

又是对上面的 美化/简化

  • @Before
  • @After
  • @AfterReturning
  • @AfterThrowing
  • @Around

官方文档

总的图 来自实验楼https://www.shiyanlou.com/courses/109

实验楼

java.lang不需要import

String 内部不可变,StringBuffer 内部可变

看到下面这图我 哇的一声就哭了

设计模式之间关系

Java 整理

core java

##《Java项目开发全程实录 第3版》个人整理

涉及知识一览

按层次

其它

按目录

  1. SQL Server 2000, PowerDesigner
  2. JavaDB
  3. Hibernate Oracle
  4. SQL Server 2005, Visio
  5. SQL Server 2000
  6. JavaDB, 短信猫 Java Mail
  7. Hibernate, Spring
  8. SQL Server 2005
  9. no Swing, jsp, javaBean, SQL Server 2000, Tomcat, Proxool
  10. Socket, thread

TODO

IoC

AOP

Spring

Swing

个人账目管理

Minimum_maintenance.cpp

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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122

//template
#include<iostream>
#include<cstdlib>
#include<assert.h>
using namespace std;
struct max_select{
int p;
int d;
double v;
bool operator > (const max_select & other) const {
return v > other.v;
}
bool operator < (const max_select & other) const {
return v < other.v;
}
bool operator == (const max_select & other) const {
return v == other.v;
}
};

template <class T>
class Minimum_maintenance {
private:
T * _stack[2]; // 0 store Descending sequence, 1 store other's
int _iter[2]; // store iter
int * _order; // for push and pop
int * _fakedeepcopy ;
public:
Minimum_maintenance(){
cout<<"NOT SUPPORT"<<endl;
assert(0);
}
Minimum_maintenance(int s){
if(s < 1)//protect
s = 1;
_iter[0] = 0;
_iter[1] = 0;
_stack[0] = new T[s];
_stack[1] = new T[s];
_order = new int[s];
_fakedeepcopy = new int [1] ;
printf("new (%08x)\n",this);
printf(" _stack[0] = (%08x)\n",_stack[0]);
printf(" _stack[1] = (%08x)\n",_stack[1]);
printf(" _order = (%08x)\n",_order);
_fakedeepcopy[0] = 0;
}
Minimum_maintenance(const Minimum_maintenance& copy){
_stack[0] = copy._stack[0];
_stack[1] = copy._stack[1];
_iter [0] = copy._iter [0];
_iter [1] = copy._iter [1];
_order = copy._order;
_fakedeepcopy = copy._fakedeepcopy;
_fakedeepcopy[0]++;
printf("Fake deepcopy %08x => %08x\n",&copy,this);
}
~Minimum_maintenance(){
printf("free(%08x)\n",this);
printf(" _fakedeepcopy = %d\n",_fakedeepcopy[0]);
printf(" _stack[0] = (%08x)\n",_stack[0]);
printf(" _stack[1] = (%08x)\n",_stack[1]);
printf(" _order = (%08x)\n",_order);
if(!_fakedeepcopy[0]){
delete [] _stack[0];
delete [] _stack[1];
delete [] _order;
}else{
_fakedeepcopy[0]--;
}
cout<<"free() finished"<<endl;
}
void push(const T & ms){
int i;
if(_iter[0] == 0 || _stack[0][_iter[0] - 1] > ms){
i = 0;
}else{
i = 1;
}
_stack[i][_iter[i]] = ms;

_order[_iter[0]+_iter[1]] = i;
_iter[i] ++ ;
}
void pop(){
if(_iter[0]+_iter[1]){
_iter[_order[ _iter[0] + _iter[1] - 1 ]]--;
}
}
bool top(T & ms){
if(!(_iter[0]+_iter[1]))
return false;
int o = _order[ _iter[0] + _iter[1] - 1];
ms = _stack[0][ _iter[0] - 1];
return true;
}
bool const empty(){
return _iter[0] == 0;
}
};

int main(){
int i;
Minimum_maintenance<max_select> mm(20);
for( i = 0; i < 20 ; i ++){
double in = rand()*1.0;
cout<<in<<endl<<"\t";
max_select inms = {1,1,in};
mm.push(inms);
while(rand()%2){
cout<< " POP ";
mm.pop();
}
max_select ms;
if(mm.top(ms))//mm.empty()
cout<<ms.v<<endl;
else
cout<<"EMPTY()"<<endl;
}
return 0;
}

Minimum_maintenance.old1.cpp

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
// just run
#include<iostream>
#include<cstdlib>
using namespace std;
class MinimumMaintenance {
private:
int * _stack[2]; // 0 store Descending sequence, 1 store other's
int _iter[2]; // store iter
int * _order; // for push and pop
public:
MinimumMaintenance(int s){
_iter[0] = 0;
_iter[1] = 0;
_stack[0] = new int[3*s];
_stack[1] = new int[3*s];
_order = new int[s];
}
~MinimumMaintenance(){
delete [] _stack[0];
delete [] _stack[1];
delete [] _order;
}
void push(int p,int d,int v){
int i;
if(_iter[0] == 0 || _stack[0][3*(_iter[0] - 1)+2] > v){
i = 0;
}else{
i = 1;
}
_stack[i][3*_iter[i] ] = p;
_stack[i][3*_iter[i] + 1] = d;
_stack[i][3*_iter[i] + 2] = v;

_order[_iter[0]+_iter[1]] = i;
_iter[i] ++ ;
}
void pop(){
if(_iter[0]+_iter[1]){
_iter[_order[ _iter[0] + _iter[1] - 1 ]]--;
}
}
bool top(int & p,int & d,int &v){
if(!(_iter[0]+_iter[1]))
return false;
int o = _order[ _iter[0] + _iter[1] - 1];
p = _stack[0][ 3 * _iter[0] - 3];
d = _stack[0][ 3 * _iter[0] - 2];
v = _stack[0][ 3 * _iter[0] - 1];
return true;
}
};
int main(){
int i;
MinimumMaintenance mm(20);
for( i = 0; i < 20 ; i ++){
int in = rand();
cout<<in<<endl<<"\t";
mm.push(1,1,in);
while(rand()%2){
cout<< " POP ";
mm.pop();
}
int a,b,c;
if(mm.top(a,b,c))
cout<<c<<endl;
else
cout<<"EMPTY()"<<endl;
}
return 0;
}

Minimum_maintenance.old2.cpp

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
//struct
#include<iostream>
#include<cstdlib>
using namespace std;
struct max_select{
int p;
int d;
double v;
};
class Minimum_maintenance {
private:
max_select * _stack[2]; // 0 store Descending sequence, 1 store other's
int _iter[2]; // store iter
int * _order; // for push and pop
public:
Minimum_maintenance(int s){
_iter[0] = 0;
_iter[1] = 0;
_stack[0] = new max_select[s];
_stack[1] = new max_select[s];
_order = new int[s];
}
~Minimum_maintenance(){
delete [] _stack[0];
delete [] _stack[1];
delete [] _order;
}
void push(const max_select & ms){
int i;
if(_iter[0] == 0 || _stack[0][_iter[0] - 1].v > ms.v){
i = 0;
}else{
i = 1;
}
_stack[i][_iter[i]] = ms;

_order[_iter[0]+_iter[1]] = i;
_iter[i] ++ ;
}
void pop(){
if(_iter[0]+_iter[1]){
_iter[_order[ _iter[0] + _iter[1] - 1 ]]--;
}
}
bool top(max_select & ms){
if(!(_iter[0]+_iter[1]))
return false;
int o = _order[ _iter[0] + _iter[1] - 1];
ms = _stack[0][ _iter[0] - 1];
return true;
}
};
int main(){
int i;
Minimum_maintenance mm(20);
for( i = 0; i < 20 ; i ++){
double in = rand()*1.0;
cout<<in<<endl<<"\t";
max_select inms = {1,1,in};
mm.push(inms);
while(rand()%2){
cout<< " POP ";
mm.pop();
}
max_select ms;
if(mm.top(ms))
cout<<ms.v<<endl;
else
cout<<"EMPTY()"<<endl;
}
return 0;
}

Minimum_maintenance.old3.cpp

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
//operator
#include<iostream>
#include<cstdlib>
using namespace std;
struct max_select{
int p;
int d;
double v;
bool operator > (const max_select & other) const {
return v > other.v;
}
bool operator < (const max_select & other) const {
return v < other.v;
}
bool operator == (const max_select & other) const {
return v == other.v;
}
};
class Minimum_maintenance {
private:
max_select * _stack[2]; // 0 store Descending sequence, 1 store other's
int _iter[2]; // store iter
int * _order; // for push and pop
public:
Minimum_maintenance(int s){
_iter[0] = 0;
_iter[1] = 0;
_stack[0] = new max_select[s];
_stack[1] = new max_select[s];
_order = new int[s];
}
~Minimum_maintenance(){
delete [] _stack[0];
delete [] _stack[1];
delete [] _order;
}
void push(const max_select & ms){
int i;
if(_iter[0] == 0 || _stack[0][_iter[0] - 1] > ms){
i = 0;
}else{
i = 1;
}
_stack[i][_iter[i]] = ms;

_order[_iter[0]+_iter[1]] = i;
_iter[i] ++ ;
}
void pop(){
if(_iter[0]+_iter[1]){
_iter[_order[ _iter[0] + _iter[1] - 1 ]]--;
}
}
bool top(max_select & ms){
if(!(_iter[0]+_iter[1]))
return false;
int o = _order[ _iter[0] + _iter[1] - 1];
ms = _stack[0][ _iter[0] - 1];
return true;
}
};
int main(){
int i;
Minimum_maintenance mm(20);
for( i = 0; i < 20 ; i ++){
double in = rand()*1.0;
cout<<in<<endl<<"\t";
max_select inms = {1,1,in};
mm.push(inms);
while(rand()%2){
cout<< " POP ";
mm.pop();
}
max_select ms;
if(mm.top(ms))
cout<<ms.v<<endl;
else
cout<<"EMPTY()"<<endl;
}
return 0;
}

Minimum_maintenance.old4.cpp

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
100
101
102
103
104
105
//template
#include<iostream>
#include<cstdlib>
using namespace std;
struct max_select{
int p;
int d;
double v;
bool operator > (const max_select & other) const {
return v > other.v;
}
bool operator < (const max_select & other) const {
return v < other.v;
}
bool operator == (const max_select & other) const {
return v == other.v;
}
};

template <class T>
class Minimum_maintenance {
private:
T * _stack[2]; // 0 store Descending sequence, 1 store other's
int _iter[2]; // store iter
int * _order; // for push and pop
public:
Minimum_maintenance(){
// CHANGE?
_iter[0] = 0;
_iter[1] = 0;
_stack[0] = new T[1];
_stack[1] = new T[1];
_order = new int[1];
}
Minimum_maintenance(int s){
_iter[0] = 0;
_iter[1] = 0;
_stack[0] = new T[s];
_stack[1] = new T[s];
_order = new int[s];
}
~Minimum_maintenance(){
delete [] _stack[0];
delete [] _stack[1];
delete [] _order;
}
void resize(int s){
delete [] _stack[0];
delete [] _stack[1];
delete [] _order;
_iter[0] = 0;
_iter[1] = 0;
_stack[0] = new T[s];
_stack[1] = new T[s];
_order = new int[s];
}
void push(const T & ms){
int i;
if(_iter[0] == 0 || _stack[0][_iter[0] - 1] > ms){
i = 0;
}else{
i = 1;
}
_stack[i][_iter[i]] = ms;

_order[_iter[0]+_iter[1]] = i;
_iter[i] ++ ;
}
void pop(){
if(_iter[0]+_iter[1]){
_iter[_order[ _iter[0] + _iter[1] - 1 ]]--;
}
}
bool top(T & ms){
if(!(_iter[0]+_iter[1]))
return false;
int o = _order[ _iter[0] + _iter[1] - 1];
ms = _stack[0][ _iter[0] - 1];
return true;
}
bool empty(){
return _iter[0] == 0;
}
};
int main(){
int i;
Minimum_maintenance<max_select> mm;
mm.resize(20);
for( i = 0; i < 20 ; i ++){
double in = rand()*1.0;
cout<<in<<endl<<"\t";
max_select inms = {1,1,in};
mm.push(inms);
while(rand()%2){
cout<< " POP ";
mm.pop();
}
max_select ms;
if(mm.top(ms))//mm.empty()
cout<<ms.v<<endl;
else
cout<<"EMPTY()"<<endl;
}
return 0;
}

permutation_traversal.cpp

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
//10 - 0.2s
#include<iostream>
using namespace std;

int pt_s;

void ptdemo(unsigned int pt_bits){
if(pt_bits == (1<<pt_s) - 1)
return ;
unsigned int i;
for(i = 0; i < pt_s ; ++i){
if( pt_bits & (1<<i) )
continue ;
//cout<<i<<endl;
int debug = i;
ptdemo(pt_bits | (1<<i));
}
return ;
}
int main(){
pt_s = 10;
int v = 0;
ptdemo(v);
return 0;
}

permutation_traversal.old1.cpp

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
//10 - 11.588 
#include<iostream>
#include<vector>
#include<stack>
using namespace std;

class Permutation_traversal{
protected:
vector<int>left_index; // to boost vector?
stack<pair<vector<int>::iterator,int>>visitstack; // to boost list?
vector<int>::iterator iter;
Permutation_traversal(const vector<int>&li,const stack<pair<vector<int>::iterator,int>>&vs)
:left_index(li),visitstack(vs){
iter = left_index.begin();
}
public:
Permutation_traversal(int s){
for(int i=0;i<s;i++){
left_index.push_back(i);
}
iter = left_index.begin();
}

bool const empty(){
return left_index.empty();
}
void next(){
if(iter == left_index.end())
return ;
++iter;
}

bool const valid(){
return iter != left_index.end();
}

int getnum(){
return visitstack.size();
}

int const getvalue(){
return iter != left_index.end() ? *iter : -1;
}
void push(){
if(iter == left_index.end())
return ;
visitstack.push(make_pair(iter,*iter));
left_index.erase(iter);
}
void pop(){
if(visitstack.empty())
return ;
pair<vector<int>::iterator,int> p = visitstack.top();
left_index.insert(p.first,p.second);
visitstack.pop();
}

Permutation_traversal * isolate(){// careful about memory overflow
return new Permutation_traversal(left_index,visitstack);
}
};

void ptdemo(Permutation_traversal & pt){
if(pt.empty())
return ;
for(;pt.valid();pt.next()){
//for(int i=0,limiti=pt.getnum();i<limiti;i++)cout<<" ";
//cout<<pt.getvalue()<<endl;
int debug = pt.getvalue();
pt.push();
Permutation_traversal * child_pt = pt.isolate();
ptdemo(*child_pt);
delete child_pt;
pt.pop();
}
return ;
}
int main(){
Permutation_traversal pt(10);
ptdemo(pt);
return 0;
}

permutation_traversal.old1.min.cpp

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
// ,min.cpp use less check
#include<iostream>
#include<vector>
#include<stack>
using namespace std;

class Permutation_traversal{
protected:
vector<int>left_index; // to boost vector?
stack<pair<vector<int>::iterator,int>>visitstack; // to boost list?
vector<int>::iterator iter;
Permutation_traversal(const vector<int>&li,const stack<pair<vector<int>::iterator,int>>&vs)
:left_index(li),visitstack(vs){
iter = left_index.begin();
}
public:
Permutation_traversal(int s){
for(int i=0;i<s;i++){
left_index.push_back(i);
}
iter = left_index.begin();
}

bool const empty(){
return left_index.empty();
}
void next(){
++iter;
}

bool const valid(){
return iter != left_index.end();
}

int const getvalue(){
return *iter;
}
void push(){
visitstack.push(make_pair(iter,*iter));
left_index.erase(iter);
}
void pop(){
pair<vector<int>::iterator,int> p = visitstack.top();
left_index.insert(p.first,p.second);
visitstack.pop();
}

Permutation_traversal * isolate(){// careful about memory overflow
return new Permutation_traversal(left_index,visitstack);
}
};

void ptdemo(Permutation_traversal & pt){
if(pt.empty())
return ;
for(;pt.valid();pt.next()){
cout<<pt.getvalue()<<endl;
pt.push();
Permutation_traversal * child_pt = pt.isolate();
ptdemo(*child_pt);
delete child_pt;
pt.pop();
}
return ;
}
int main(){
Permutation_traversal pt(5);
ptdemo(pt);
return 0;
}

permutation_traversal.old2.cpp

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
//10 4.469s
#include<iostream>
#include<vector>
using namespace std;

class Permutation_traversal{
protected:
vector<int>left_index; // to boost vector?
vector<int>::iterator iter;
Permutation_traversal(const vector<int>&li)
:left_index(li){
iter = left_index.begin();
}
public:
Permutation_traversal(int s){
for(int i=0;i<s;i++){
left_index.push_back(i);
}
iter = left_index.begin();
}

bool const empty(){
return left_index.empty();
}
void next(){
if(iter == left_index.end())
return ;
++iter;
}

bool const valid(){
return iter != left_index.end();
}


int const getvalue(){
return iter != left_index.end() ? *iter : -1;
}

Permutation_traversal * isolate(){// careful about memory overflow
if(iter == left_index.end())
return NULL;
vector<int>::iterator tmp_iter = iter;
int tmp_val = *iter;
left_index.erase(iter);
Permutation_traversal * newpt = new Permutation_traversal(left_index);
left_index.insert(tmp_iter,tmp_val);
return newpt;
}
// debug [TODO]remove code below
int getnum(){
return 5-left_index.size();
}
};

void ptdemo(Permutation_traversal & pt){
if(pt.empty())
return ;
for(;pt.valid();pt.next()){
//for(int i=0,limiti=pt.getnum();i<limiti;i++)cout<<" ";
//cout<<pt.getvalue()<<endl;
int debug = pt.getvalue();
Permutation_traversal * child_pt = pt.isolate();
ptdemo(*child_pt);
delete child_pt;
}
return ;
}
int main(){
Permutation_traversal pt(10);
ptdemo(pt);
return 0;
}

permutation_traversal.old2.min.cpp

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
#include<iostream>
#include<vector>
#include<stack>
using namespace std;

class Permutation_traversal{
protected:
vector<int>left_index; // to boost vector?
vector<int>::iterator iter;
Permutation_traversal(const vector<int>&li)
:left_index(li){
iter = left_index.begin();
}
public:
Permutation_traversal(int s){
for(int i=0;i<s;i++){
left_index.push_back(i);
}
iter = left_index.begin();
}

bool const empty(){
return left_index.empty();
}
void next(){
++iter;
}

bool const valid(){
return iter != left_index.end();
}


int const getvalue(){
return *iter;
}

Permutation_traversal * isolate(){// careful about memory overflow
vector<int>::iterator tmp_iter = iter;
int tmp_val = *iter;
left_index.erase(iter);
Permutation_traversal * newpt = new Permutation_traversal(left_index);
left_index.insert(tmp_iter,tmp_val);
return newpt;
}
// debug [TODO]remove code below
int getnum(){
return 5-left_index.size();
}
};

void ptdemo(Permutation_traversal & pt){
if(pt.empty())
return ;
for(;pt.valid();pt.next()){
for(int i=0,limiti=pt.getnum();i<limiti;i++)cout<<" ";
cout<<pt.getvalue()<<endl;
Permutation_traversal * child_pt = pt.isolate();
ptdemo(*child_pt);
delete child_pt;
}
return ;
}
int main(){
Permutation_traversal pt(5);
ptdemo(pt);
return 0;
}

permutation_traversal.old3.cpp

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
//10 - 0.927s
#include<iostream>
using namespace std;

class Permutation_traversal{
protected:
int * left_index; // to boost vector?
int size;
int iter;
Permutation_traversal(){
}
public:
Permutation_traversal(int s)
:size(s),iter(0){
left_index = new int[s];
for(int i=0;i<s;i++){
left_index[i]=i;
}
}
~Permutation_traversal(){
delete [] left_index;
}
bool const empty(){
return size == 0;
}
void next(){
if(iter == size)
return ;
++iter;
}

bool const valid(){
return iter != size;
}

int const getvalue(){
return iter != size ? left_index[iter] : -1;
}

Permutation_traversal * isolate(){// careful about memory overflow
if(iter == size)
return NULL;
Permutation_traversal * newpt = new Permutation_traversal();
newpt->left_index = new int[size-1];
newpt->size = 0;
newpt->iter = 0;
for(int it = 0 ; it < size ; ++it){
if(it == iter)
continue;
newpt->left_index[newpt->size++] = left_index[it];
}
return newpt;
}
// debug [TODO]remove code below
int getnum(){
return 5-size;
}
};

void ptdemo(Permutation_traversal & pt){
if(pt.empty())
return ;
for(;pt.valid();pt.next()){
//for(int i=0,limiti=pt.getnum();i<limiti;i++)cout<<" ";
//cout<<pt.getvalue()<<endl;
int debug = pt.getvalue();
Permutation_traversal * child_pt = pt.isolate();
ptdemo(*child_pt);
delete child_pt;
}
return ;
}
int main(){
Permutation_traversal pt(10);
ptdemo(pt);
return 0;
}

permutation_traversal.old3.min.cpp

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
#include<iostream>
#include<vector>
#include<stack>
using namespace std;

class Permutation_traversal{
protected:
int * left_index; // to boost vector?
int size;
int iter;
Permutation_traversal(){
}
public:
Permutation_traversal(int s)
:size(s),iter(0){
left_index = new int[s];
for(int i=0;i<s;i++){
left_index[i]=i;
}
}
~Permutation_traversal(){
delete [] left_index;
}
bool const empty(){
return size == 0;
}
void next(){
++iter;
}

bool const valid(){
return iter != size;
}

int const getvalue(){
return left_index[iter];
}

Permutation_traversal * isolate(){// careful about memory overflow
Permutation_traversal * newpt = new Permutation_traversal();
newpt->left_index = new int[size-1];
newpt->size = 0;
newpt->iter = 0;
for(int it = 0 ; it < size ; ++it){
if(it == iter)
continue;
newpt->left_index[newpt->size++] = left_index[it];
}
return newpt;
}
// debug [TODO]remove code below
int getnum(){
return 5-size;
}
};

void ptdemo(Permutation_traversal & pt){
if(pt.empty())
return ;
for(;pt.valid();pt.next()){
for(int i=0,limiti=pt.getnum();i<limiti;i++)cout<<" ";
cout<<pt.getvalue()<<endl;
Permutation_traversal * child_pt = pt.isolate();
ptdemo(*child_pt);
delete child_pt;
}
return ;
}
int main(){
Permutation_traversal pt(5);
ptdemo(pt);
return 0;
}

permutation_traversal.old4.cpp

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
100
101
102
//10 - 0.581s
#include<iostream>
using namespace std;

class Permutation_traversal{
private:
class Child_Permutation_traversal{
public:
int * left_index; // to boost vector?
int size;
int iter;
Child_Permutation_traversal(int s)
:size(s),iter(0){
left_index = new int[s];
}
~Child_Permutation_traversal(){
delete [] left_index;
}
};

Child_Permutation_traversal ** cpt;
int size;
int depth;
public:
Permutation_traversal(int s)
:size(s){
cpt = new Child_Permutation_traversal * [s + 1];
int i;
for(i = 0; i <= s; i++){
cpt[i] = new Child_Permutation_traversal(s-i);
}
for(i = 0; i < s; i++){
cpt[0]->left_index[i]=i;
}
depth = 0;
}
~Permutation_traversal(){
for(int i=0;i<=size;i++){
delete cpt[i];
}
delete [] cpt;
}
bool const empty(){
return cpt[depth]->size == 0;
}
void next(){
if(cpt[depth]->iter == cpt[depth]->size)
return ;
++(cpt[depth]->iter);
}

bool const valid(){
return cpt[depth]->iter != cpt[depth]->size;
}

int const getvalue(){
return cpt[depth]->iter != cpt[depth]->size ? cpt[depth]->left_index[cpt[depth]->iter] : -1;
}

void select(){
if(cpt[depth]->iter == cpt[depth]->size)
return ;
int newdepth = depth + 1;
cpt[newdepth]->size = 0;
cpt[newdepth]->iter = 0;
for(int it = 0,itlimit=cpt[depth]->size ; it < itlimit ; ++it){
if(it == cpt[depth]->iter)
continue;
cpt[newdepth]->left_index[cpt[newdepth]->size++] = cpt[depth]->left_index[it];
}
depth = newdepth;
}

void unselect(){
if(depth > 0)
--depth;
}

int getnum(){
return 5-cpt[depth]->size;
}
};

void ptdemo(Permutation_traversal & pt){
if(pt.empty())
return ;
for(;pt.valid();pt.next()){
//for(int i=0,limiti=pt.getnum();i<limiti;i++)cout<<" ";
//cout<<pt.getvalue()<<endl;
int debug = pt.getvalue();
pt.select();
ptdemo(pt);
pt.unselect();
}
return ;
}
int main(){
Permutation_traversal pt(10);
ptdemo(pt);
return 0;
}

permutation_traversal.old4.min.cpp

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
//10 - 0.472s
#include<iostream>
using namespace std;

class Permutation_traversal{
private:
class Child_Permutation_traversal{
public:
int * left_index; // to boost vector?
int size;
int iter;
Child_Permutation_traversal(int s)
:size(s),iter(0){
left_index = new int[s];
}
~Child_Permutation_traversal(){
delete [] left_index;
}
};

Child_Permutation_traversal ** cpt;
int size;
int depth;
public:
Permutation_traversal(int s)
:size(s){
cpt = new Child_Permutation_traversal * [s + 1];
int i;
for(i = 0; i <= s; i++){
cpt[i] = new Child_Permutation_traversal(s-i);
}
for(i = 0; i < s; i++){
cpt[0]->left_index[i]=i;
}
depth = 0;
}
~Permutation_traversal(){
for(int i=0;i<=size;i++){
delete cpt[i];
}
delete [] cpt;
}
bool const empty(){
return cpt[depth]->size == 0;
}
void next(){
++(cpt[depth]->iter);
}

bool const valid(){
return cpt[depth]->iter != cpt[depth]->size;
}

int const getvalue(){
return cpt[depth]->left_index[cpt[depth]->iter];
}

void select(){
int newdepth = depth + 1;
cpt[newdepth]->size = 0;
cpt[newdepth]->iter = 0;
for(int it = 0,itlimit=cpt[depth]->size ; it < itlimit ; ++it){
if(it == cpt[depth]->iter)
continue;
cpt[newdepth]->left_index[cpt[newdepth]->size++] = cpt[depth]->left_index[it];
}
depth = newdepth;
}

void unselect(){
--depth;
}

int getnum(){
return 5-cpt[depth]->size;
}
};

void ptdemo(Permutation_traversal & pt){
if(pt.empty())
return ;
for(;pt.valid();pt.next()){
//for(int i=0,limiti=pt.getnum();i<limiti;i++)cout<<" ";
//cout<<pt.getvalue()<<endl;
int debug = pt.getvalue();
pt.select();
ptdemo(pt);
pt.unselect();
}
return ;
}
int main(){
Permutation_traversal pt(10);
ptdemo(pt);
return 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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
# coding: utf-8

__version__ = '1.1.0'
__author__ = 'Zhu Jianqi (heloowird@gmail.com)'

'''
以关键词收集新浪微博
'''
import requests
import wx
import csv
import codecs
import sys
import urllib
import urllib2
import re
import json
import hashlib
import os
import time
import datetime
import random
from lxml import etree
import logging
import gzip
from StringIO import StringIO

class CollectData():
"""数据收集类
利用微博高级搜索功能,按关键字搜集一定时间范围内的微博。

大体思路:构造URL,爬取网页,然后解析网页中的微博ID。后续利用微博API进行数据入库。本程序只负责收集微博的ID。

登陆新浪微博,进入高级搜索,输入关键字”空气污染“,选择”实时“,时间为”2013-07-02-2:2013-07-09-2“,地区为”北京“,之后发送请求会发现地址栏变为如下:
http://s.weibo.com/wb/%25E7%25A9%25BA%25E6%25B0%2594%25E6%25B1%25A1%25E6%259F%2593&xsort=time&region=custom:11:1000&timescope=custom:2013-07-02-2:2013-07-09-2&Refer=g

是不是很长,其实很简单。
固定地址部分:http://s.weibo.com/wb/
关键字二次UTF-8编码:%25E7%25A9%25BA%25E6%25B0%2594%25E6%25B1%25A1%25E6%259F%2593
排序为“实时”:xsort=time
搜索地区:region=custom:11:1000
搜索时间范围:timescope=custom:2013-07-02-2:2013-07-09-2
可忽略项:Refer=g
显示类似微博:nodup=1 注:这个选项可多收集微博,建议加上。默认不加此参数,省略了部分相似微博。
某次请求的页数:page=1

另外,高级搜索最多返回50页微博,那么时间间隔设置最小为宜。所以该类设置为搜集一定时间段内最多50页微博。
"""
def __init__(self, keyword, startTime, savedir, interval='50', flag=True, begin_url_per = "http://s.weibo.com/weibo/"):
self.begin_url_per = begin_url_per #设置固定地址部分,默认为"http://s.weibo.com/weibo/",或者"http://s.weibo.com/wb/"
self.setKeyword(keyword) #设置关键字
self.setStartTimescope(startTime) #设置搜索的开始时间
# self.setRegion(region) #设置搜索区域
self.setSave_dir(savedir) #设置结果的存储目录
self.setInterval(interval) #设置邻近网页请求之间的基础时间间隔(注意:过于频繁会被认为是机器人)
self.setFlag(flag) #设置
self.logger = logging.getLogger('main.CollectData') #初始化日志

##设置关键字
##关键字需解码
def setKeyword(self, keyword):
#self.keyword = keyword.decode('GBK').encode("utf-8")
self.keyword = keyword
print 'twice encode:',self.getKeyWord()

##设置起始范围,间隔为1小时
##格式为:yyyy-mm-dd-HH
def setStartTimescope(self, startTime):
if not (startTime == '-'):
self.timescope = startTime + ":" + startTime
else:
self.timescope = '-'

# ##设置搜索地区
# def setRegion(self, region):
# self.region = region

##设置结果的存储目录
def setSave_dir(self, save_dir):
self.save_dir = save_dir
if not os.path.exists(self.save_dir):
os.mkdir(self.save_dir)

##设置邻近网页请求之间的基础时间间隔
def setInterval(self, interval):
self.interval = int(interval)

##设置是否被认为机器人的标志。若为False,需要进入页面,手动输入验证码
def setFlag(self, flag):
self.flag = flag

##构建URL
def getURL(self):
return self.begin_url_per+self.getKeyWord()+"&typeall=1&suball=1"+"&timescope=custom:"+self.timescope+"&page="

##关键字需要进行两次urlencode
def getKeyWord(self):
once = urllib.urlencode({"kw":self.keyword})[3:]
return urllib.urlencode({"kw":once})[3:]

##爬取一次请求中的所有网页,最多返回50页
def download(self, url, maxTryNum=4):
csvFile = open(self.save_dir + os.sep + "weibo_kanbing.csv", "ab") #向结果文件中写微博ID
csvFile.write(codecs.BOM_UTF8)
content = csv.writer(csvFile, dialect='excel')
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'}
cookie = {'SINAGLOBAL':'3726160468139.8677.1489128973894', 'un':'18621677460', 'wvr':'6', 'SWB':'usrmdinst_12', 'SCF':'At4nsWXnBTiLQgwnhEdGW1ipfDRoyBYdEIpm4KN7_ZN3C0BxRlQeyX0sHoQOK6bDqLR6HeBBiwo6wRFXfObIvnc.', 'SUB':'_2A251wx_bDeRxGeNP7FIR9yjFwzyIHXVWuXYTrDV8PUNbmtBeLRjVkW8ia3o1WnWjknWq3t_Uh0UkKzBqsg..', 'SUBP':'0033WrSXqPxfM725Ws9jqgMF55529P9D9Wh_ODAX.pd3QJ6U3yvqGKET5JpX5KMhUgL.Fo-pS057S0q41h52dJLoIEUBBEXLxKqL1hnL1KnLxK-LBKeLB-zLxK-L1K5L1K2LxK-L12qLBoet', 'SUHB':'0vJ4Ss25HO1Ohu', 'ALF':'1521001227', 'SSOLoginState':'1489465228', '_s_tentry':'login.sina.com.cn', 'Apache':'7301168373695.357.1489465207066', 'ULV':'1489465207130:8:8:5:7301168373695.357.1489465207066:1489412710557', 'UOR':',,login.sina.com.cn', 'WBStorage':'02e13baf68409715|undefined'}

hasMore = True #某次请求可能少于50页,设置标记,判断是否还有下一页
isCaught = False #某次请求被认为是机器人,设置标记,判断是否被抓住。抓住后,需要复制log中的文件,进入页面,输入验证码
filter = set([]) #过滤重复的微博ID

i = 1 #记录本次请求所返回的页数
while hasMore and i < 51 and (not isCaught): #最多返回50页,对每页进行解析,并写入结果文件
source_url = url + str(i) #构建某页的URL
data = '' #存储该页的网页数据
goon = True #网络中断标记

##网络不好的情况,试着尝试请求三次
for tryNum in range(maxTryNum):
try:
# set header http://stackoverflow.com/questions/385262/how-do-i-send-a-custom-header-with-urllib2-in-a-http-request
# see this http://stackoverflow.com/questions/1653591/python-urllib2-response-header , so you can see 'gzip' in response header with urllib2.urlopen(URL).info()
# and this http://stackoverflow.com/questions/3947120/does-python-urllib2-automatically-uncompress-gzip-data-fetched-from-webpage teach you how to decode gzip
#
#r = requests.get(source_url, cookies=cookie, headers=headers, timeout=12)
send_headers = {
"Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"Accept-Encoding":"gzip, deflate, sdch",
"Accept-Language":"zh-CN,zh;q=0.8,en;q=0.6",
"Cache-Control":"no-cache",
"Connection":"keep-alive",
#"Cookie":"cookies here"
"Host":"s.weibo.com",
"Pragma":"no-cache",
"Referer":"http://s.weibo.com/",
"Upgrade-Insecure-Requests":"1",
"User-Agent":"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36"
}
req = urllib2.Request(source_url , headers=send_headers)
r = urllib2.urlopen(req)
if r.info().get('Content-Encoding') == 'gzip':
buf = StringIO(r.read())
f = gzip.GzipFile(fileobj=buf)
html = f.read()
else:
html = r.read()
data = html
#print data
break
except:
if tryNum < (maxTryNum-1):
time.sleep(10)
else:
print 'Internet Connect Error!'
self.logger.error('Internet Connect Error!')
self.logger.info('filePath: ' + self.save_dir)
self.logger.info('url: ' + source_url)
self.logger.info('fileNum: ' + str(fileNum))
self.logger.info('page: ' + str(i))
self.flag = False
goon = False
break
if goon:
lines = data.splitlines()
isCaught = True
for line in lines:
## 判断是否有微博内容,出现这一行,则说明没有被认为是机器人
if line.startswith('<script>STK && STK.pageletM && STK.pageletM.view({"pid":"pl_weibo_direct"'):
isCaught = False
n = line.find('html":"')
if n > 0:
j = line[n + 7: -12].encode("utf-8").decode('unicode_escape').encode("utf-8").replace("\\", "").decode('utf-8')
## 没有更多结果页面
if (j.find('<div class="search_noresult">') > 0):
hasMore = False
## 有结果的页面
else:
page = etree.HTML(j)
comment_box = page.xpath("//div[@action-type=\"feed_list_item\"]")
for each_comment in comment_box:
comment_time = each_comment.xpath(".//div[@class=\"feed_from W_textb\"]/a/@title")
comment_text_list = each_comment.xpath(".//p[@class='comment_txt']")
comment_text = []
for eachtext in comment_text_list:
comment_text = 'r'.join(eachtext.xpath(".//text()"))
comment_text = comment_text.replace(' ','').replace('\n', '').replace('\r', ' ')
comment_text = comment_text.encode('utf8')
if (comment_text != 'None' and comment_text not in filter):
filter.add(comment_text)
content.writerow([comment_time[0], comment_text])
# weibo = page.xpath("//div[@class=\"feed_from W_textb\"])
# for weibo_time, weibo_content in weibo:
# weibo_time = weibo_time.xpath("./[@class=\"feed_from W_textb\"]/a/@title")
# concept = 'r'.join(weibo_content.xpath("./text()"))
# concept = concept.replace(' ','').replace('\n','').replace('\r',' ')
# concept = concept.encode('utf8')
# if (concept != 'None' and concept not in filter):
# filter.add(concept)
# content.writerow([weibo_time, concept])

# dls_id = page.xpath("//div[@class=\"feed_from W_textb\"]/a/@title")
# for dl_id in dls_id:
# # mid = str(dl_id.attrib.get('nick-name'))
# dl_id = dl_id.encode('utf8')
# if (dl_id != 'None' and dl_id not in mid_filter):
# mid_filter.add(dl_id)
# content.writerow([dl_id])
#
# dls_text = page.xpath("//p[@class='comment_txt']")
# for dl_text in dls_text:
# concept = 'r'.join(dl_text.xpath("./text()"))
# concept = concept.replace(' ','').replace('\n','').replace('\r',' ')
# concept = concept.encode('utf8')
# if (concept != 'None' and concept not in mid_filter):
# mid_filter.add(concept)
# content.writerow([concept])
# content.writerow('\n')
# if (concept != 'None' and concept not in mid_filter):
# mid_filter.add(concept)
# content.write(concept)
# content.write('\n')
# print concept
# print "----------------------"
break
lines = None
## 处理被认为是机器人的情况
if isCaught:
print 'Be Caught!'
self.logger.error('Be Caught Error!')
self.logger.info('filePath: ' + self.save_dir)
self.logger.info('url: ' + source_url)
self.logger.info('fileNum: ' + str(fileNum))
self.logger.info('page:' + str(i))
data = None
self.flag = False
break
## 没有更多结果,结束该次请求,跳到下一个请求
if not hasMore:
print 'No More Results!'
if i == 1:
time.sleep(random.randint(55,75))
else:
time.sleep(15)
data = None
break
i += 1
## 设置两个邻近URL请求之间的随机休眠时间,防止Be Caught。目前没有模拟登陆
# sleeptime_one = random.randint(self.interval-30,self.interval-10)
# sleeptime_two = random.randint(self.interval+10,self.interval+30)
# if i%2 == 0:
# sleeptime = sleeptime_two
# else:
# sleeptime = sleeptime_one
# print 'sleeping ' + str(sleeptime) + ' seconds...'
# time.sleep(sleeptime)
else:
break
csvFile.close()
csvFile = None

##改变搜索的时间范围,有利于获取最多的数据
def getTimescope(self, perTimescope, hours):
if not (perTimescope=='-'):
times_list = perTimescope.split(':')
start_datetime = datetime.datetime.fromtimestamp(time.mktime(time.strptime(times_list[-1],"%Y-%m-%d-%H")))
start_new_datetime = start_datetime + datetime.timedelta(seconds = 3600)
end_new_datetime = start_new_datetime + datetime.timedelta(seconds = 3600*(hours-1))
start_str = start_new_datetime.strftime("%Y-%m-%d-%H")
end_str = end_new_datetime.strftime("%Y-%m-%d-%H")
return start_str + ":" + end_str
else:
return '-'

def main():
logger = logging.getLogger('main')
logFile = './collect.log'
logger.setLevel(logging.DEBUG)
filehandler = logging.FileHandler(logFile)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s: %(message)s')
filehandler.setFormatter(formatter)
logger.addHandler(filehandler)

while True:
## 接受键盘输入
keyword = raw_input('Enter the keyword(type \'quit\' to exit ):')
if keyword == 'quit':
sys.exit()
startTime = raw_input('Enter the start time(Format:YYYY-mm-dd-HH):')
# region = raw_input('Enter the region([BJ]11:1000,[SH]31:1000,[GZ]44:1,[CD]51:1):')
savedir = raw_input('Enter the save directory(Like C://data//):')
interval = raw_input('Enter the time interval( >30 and deafult:50):')

##实例化收集类,收集指定关键字和起始时间的微博
cd = CollectData(keyword, startTime, savedir, interval)
while cd.flag:
print cd.timescope
logger.info(cd.timescope)
url = cd.getURL()
cd.download(url)
cd.timescope = cd.getTimescope(cd.timescope,1) #改变搜索的时间,到下一个小时
else:
cd = None
print '-----------------------------------------------------'
print '-----------------------------------------------------'
else:
logger.removeHandler(filehandler)
logger = None
if __name__ == '__main__':
main()

四种指针

参考文


个人整理

四个智能指针: auto_ptr, shared_ptr, weak_ptr, unique_ptr 其中后三个是c++11支持,并且第一个已经被c++11弃用。

用于测试的结构体

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
class Test
{
public:
Test(string s)
{
str = s;
cout<<"Test creat\n";
}
~Test()
{
cout<<"Test delete:"<<str<<endl;
}
string& getStr()
{
return str;
}
void setStr(string s)
{
str = s;
}
void print()
{
cout<<str<<endl;
}
private:
string str;
};

auto_ptr

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
int main()
{
auto_ptr<Test> ptest(new Test("123"));
ptest->setStr("hello 0");
ptest->print();
ptest.get()->print();
ptest->getStr() += "world !";
(*ptest).print();
ptest.reset(new Test("567"));
ptest->print();

auto_ptr<Test> ptest(new Test("789"));
auto_ptr<Test> ptest2(new Test("JQK"));
ptest2 = ptest;
ptest2->print();
if(ptest.get() == NULL)cout<<"ptest = NULL\n";
return 0;
}

输出

1
2
3
4
5
6
7
8
9
10
11
12
13
Test creat
hello 0
hello 0
hello 0world !
Test creat
Test delete:hello 0world !
567
Test creat
Test creat
Test delete:JQK
789
Test delete:789
Test delete:567

unique_ptr

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
unique_ptr<Test> fun()
{
return unique_ptr<Test>(new Test("789"));
}
int main()
{
unique_ptr<Test> ptest(new Test("123"));
unique_ptr<Test> ptest2(new Test("456"));
ptest->print();
ptest2 = std::move(ptest);//不能直接ptest2 = ptest
if(ptest == NULL)cout<<"ptest = NULL\n";
Test* p = ptest2.release();
p->print();
ptest.reset(p);
ptest->print();
ptest2 = fun(); //这里可以用=,因为使用了移动构造函数
ptest2->print();
return 0;
}

输出

1
2
3
4
5
6
7
8
9
10
11
Test creat
Test creat
123
Test delete:456
ptest = NULL
123
123
Test creat
789
Test delete:789
Test delete:123

share_ptr

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int main()
{
shared_ptr<Test> ptest(new Test("123"));
shared_ptr<Test> ptest2(new Test("456"));
cout<<ptest2->getStr()<<endl;
cout<<ptest2.use_count()<<endl;
ptest = ptest2;//"456"引用次数加1,“123”销毁
ptest->print();
cout<<ptest2.use_count()<<endl;//2
cout<<ptest.use_count()<<endl;//2
ptest.reset();
ptest2.reset();//此时“456”销毁
cout<<"done !\n";
return 0;
}

输出

1
2
3
4
5
6
7
8
9
Test creat
Test creat
456
1
Test delete:123
456
2
2
Test delete:456

总结

auto_ptr

  • 手动释放资源 .reset()
  • 将指针置空,返回资源控制权 .release()
  • .get()==NULL 判断是否为空

unique_ptr

  • auto_ptr相似
  • 不能使用两个智能指针赋值操作,应该使用std::move
  • 可以直接用if(ptest == NULL)来判断是否空指针

share_ptr

  • 使用计数机制来表明资源被几个指针共享,.use_count()来查看资源的所有者个数
  • 没有release

weak_ptr

  • weak_ptr是用来解决shared_ptr相互引用时的死锁问题,如果说两个shared_ptr相互引用,那么这两个指针的引用计数永远不可能下降为0,资源永远不会释放。它是对对象的一种弱引用,不会增加对象的引用计数,和shared_ptr之间可以相互转化,shared_ptr可以直接赋值给它,它可以通过调用lock函数来获得shared_ptr。

很久以前就有听说这个命题

但我始终也不能说出个所以然,最多的个人体验也就是root权限

知乎这种逐渐变为垃圾问答区的地方,显然是大量的0说服力的答案,慢慢变成百度知道了:-)

搜了一篇 当做英文休闲阅读了

original link

写在前面

  • windows的想法是好的,闭源比开源更难攻击
  • 事实上并没有得到预期的更好,由永无休止的补丁可证(?啊,Linux 没补丁的咯?)

这里的意思并没有反驳闭源的安全性比开源更好 同样的linux(闭) > linux(开) > windows(闭) > 同样的windows(开)

安全性:同样A,A(闭源) > A(开源),但开源带来的可以让A变成A+ 那么安全性上,A+(开) 是可能 > A(闭)

权限

windows

  • 日常运行 对于文件:高权限
  • 能够操作任何电脑上任何文件

Linux

  • 日常运行 对于文件:低权限
  • 只能操作当前用户有权限的文件

也就是说用户的文件等在Linux 还是有同样的风险?

这里原文没有说细,[对于不同用户,windows是可以操作他人的文件,而linux可一通过权限控制在一个用户内+共享?]

小总结:Linux 也不是绝对可靠

  • 更难发生系统级别的破坏
  • 更难发生用户层面广泛的破坏

社社社…社会工程学

好吧 说得有那么一点道理 (这里也有执行时需要权限属于上一部分的东西)

病毒呢 传播时 通常诱导用户添加/点击/安装

说是windos呢 例子:给个带exe附件的邮件并诱导你下载点击,然后 就完事了 (简言之 点3下就可以入侵)

但是linux呢 你下下来给它执行权限chmod么才行(简言之 要执行过程复杂繁琐+运行有系统级别破坏时需要系统权限)

个人看法

  • 不认可
  • 如果把两边用户交换一下,linux 也能提供点3下就执行程序的,并且目前的易用操作系统的流程已经很简洁了
  • 感觉这一点 大自和用户习惯,使用方式,社区安全,用的人少相联系

单种效应

…….这个名词 瞎翻译的,说的是 windows就一个,但linux 有各种分支,不同的邮件客户端,不同的架构,然后病毒的兼容性很难实现…..

仔细想一想 还是有那么些道理的 但我只想到作为server端,比如架构

外网—我们的linux1—我们的linux2—我们的linux3—我们的linux4(服务)—我们的linux5(数据)

那么要从外网进攻, 至少需要4个不同兼容性 而window就just do it again....
讲道理的话....真有做这么多层这样防护的吗,目前只了解到 有 外网-server1-服务-数据这样的

以及,本身作为非系统的server的话,在不同的linux之间的移植能力,也会比 攻击程序 的移植能力强。

感觉有那么一些道理,对我还不是太有说服力,感觉比第二点说服力强很多

用户多

个人看法

  • 不认可
  • 这只能说可能是 当下linux当下window安全的一个原因
  • 并不想讨论当下 我更喜欢数学上的 如果有相同的用户量呢 如果linux 比windows用户更多呢,如果真的是因为用户少而更安全,那我认为是无数学上的优势的
  • 其它看法linux desktop 少,但linux server多啊 虽然数据并不多到那里去数据

开源

就是上面我自己碎碎念的

大量的人能看到代码的bug,并及时去维护。

有利有弊吧

总结

啊,唯一让我满意一点的就是权限的说明了…

这篇文章也没有深入到系统里,感觉还是很表面的东西,不过windows也不开源,不知道能不能找到逆向工程出来的系统级别的,和linux的系统级别的深入比较的文章。。。恩 我不打算自己研究 还是看文章好了,期望能找到

之后在一个长篇的知乎回答上得到了一点对于权限的补充说明”其繁殖速度必须超过其死亡(被消灭)的速度”

所以,我现在能想到一个没有杀软的linux的进攻(相对于windows点3下)即是 下载并运行(社会工程学:-))->写入用户的需要管理员权限的可执行文件/脚本文件?->用户执行了它->达到和windows点3下同样能达到的效果

0%